I have this piece of code to validate an input, this input is relative to a bet made by an user
the code I have right now is the following:
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf(input + " is not a valid number.\n");
}
number = scanner.nextInt();
} while (number < 0);
System.out.printf("You have entered the number " + number);
I have the 1. and 2. figure it out with this code, but I can't for nothing add the third (3.) statement as it asks for double the same input or it gives an error InputMismatchException because it suppose to be an integer, but on test sometimes does that.
the number is suppose to be the bet
Please help xD
You logic is rather convoluted and hard to follow. I think after this assignment you should ask for some help and find a better way to structure this code. (For now, instructors usually require you to turn in your own work so I'm not going to try to change your code.)
The way you have the code now you'll have to do the final check in two parts. First, check and then decide whether to print the error message. Second, check and decide whether to continue the loop.
do {
System.out.print("Please enter a positive number: ");
while (!scanner.hasNextInt()) {
String input = scanner.next();
System.out.printf(input + " is not a valid number.\n");
}
number = scanner.nextInt();
if( number > credits )
System.out.println( "Not enough credits." );
} while (number < 0 || number > credits);
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.