Reputation: 11
I am trying to create code that validates a number. If the number is lower than 10 or higher than 20, the value of the number will be changed to 15.
Here is the code:
public class test {
public static void main(String[] args) {
int number;
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
number = input.nextInt();
validateNumber(number);
System.out.println(number);
}
public static int validateNumber(int number) {
if (number < 10 || number > 20) {
number = 15;
}
return number;
}
}
The change in the method doesn't do anything in the main method.
Upvotes: 0
Views: 33
Reputation: 859
You have two ways to do this:
1. Direct printing with function call :
int number;
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
number = input.nextInt();
System.out.println(validateNumber(number));
2. Storage in a variable, then using it:
int number;
Scanner input = new Scanner(System.in);
System.out.print("Enter Number: ");
number = input.nextInt();
int output = validateNumber(number);
System.out.println(output);
Upvotes: 0
Reputation: 11
You already return an Integer. so just do:
number = validateNumber(number);
Thus it will override the number
with the return value of the function.
Upvotes: 1