I am trying to create a program where I use the getInt method to make sure that the user enters a positive number. I have this so far
public class Binary {
public static void main(String [ ] args) {
Scanner CONSOLE = new Scanner(System.in);
int decimal=getInt(CONSOLE, "Enter a positive integer: ");
}
public static int getInt(Scanner CONSOLE, String prompt) {
System.out.print(prompt);
while (!CONSOLE.hasNextInt()) {
CONSOLE.next();
System.out.println("Not an integer; try again.");
System.out.println(prompt);
}
int posInt=CONSOLE.nextInt();
while (posInt <= 0) {
System.out.println("Not a positive integer; try again.");
CONSOLE.next();
System.out.println(prompt);
}
return CONSOLE.nextInt();
}
}
The issue occurs that when the user does enter a positive number it still disregards the input and asks the user to enter a positive integer again. I guess I'm just not exiting the loop correctly but I'm not sure how.
Your problem is return CONSOLE.nextInt();
At the end of your method, you are calling CONSOLE.nextInt()
which asks for input once more.
Return posInt
, and you'll be fine.
Best of luck, HTH
Like the others said you can return posInt
and you should be fine.
But i have some recommendations for your getInt
method:
public static int getInt(Scanner CONSOLE, String prompt) {
//initialize vars
boolean valid = false;
int posInt = 0;
//while the input is not valid, loop over the evaluation
while(!valid){
System.out.print(prompt);
if (!CONSOLE.hasNextInt()) {
CONSOLE.next();
System.out.println("Not an integer; try again.");
//"continue" stops the loop here and starts it from the beginning
continue;
}
posInt=CONSOLE.nextInt();
if (posInt > 0) {
//valid = true will get us out of the loop
valid = true;
}else {
System.out.println("Not a positive integer; try again.");
}
}
return posInt;
}
This code will reevaluate the input from the beginning if the input before was invalid.
In your code if you enter a negative int you will be prompted to reenter a number.
But since you are already in the while (posInt <= 0)
loop, it does not recheck if you actually enter a valid input.
The code i provided reevaluates the next input from the beginning until it is found valid.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.