Reputation: 3
I'm making a madlibs and one of my questions is for the user to input a whole number between 1 - 12, so I can use it to make a time. ei. I leave home at 6 PM.
This is the code I've done, but its not working. I'm not sure how to approach this. If the user inputs an invalid answer, the question repeats until a valid answer is submitted.
Scanner input = new Scanner(System.in);
int hourstime;
System.out.print("Give me another whole number between 1 and 12. ");
while (!input.hasNextInt()) {
System.out.println("That's not a number!");
input.next();
}
while (input.hasNextDouble()) {
System.out.println("I need a whole number. ");
input.next();
}
while (input.hasNextInt() >= 13 || input.hasNextInt() <= 0) {
System.out.println("I need a number between 1 and 12. ");
input.next();
}
hourTimes= input.nextInt();
System.out.println("Thanks. The time would be " + hours time + " P.M.");
Upvotes: 0
Views: 712
Reputation: 40034
You need to assign the number to a variable like I've shown here.
Scanner input = new Scanner(System.in)
int value = 0;
while (true) {
System.out.print("Please enter a value between 1 and 12: ");
value = input.nextInt();
if (value >= 1 && value <= 12) {
break;
}
System.out.println("That is not within the range!");
}
// now do something with value.
You can use that as a model for the other prompts as well.
Also note that the hasNext
methods return a boolean (true or false)
and not a number. When prompting from the console you don't really need them if you structure your code correctly. I tend to use them only when reading from a file.
In general.
Upvotes: 1
Reputation: 3491
That code will not work because the hasNext...()
methods are boolean - they only return an answer to the question whether there is any object of the respective type waiting in the stream, not what the object is.
However, if you use hasNext...()
in combination with next...()
, you will run into another problem - namely, every application of next...()
moves the cursor. That is, there is no "peek" method implemented in Scanner
.
Basically, the closest that you can do is:
In other words, something like:
if (input.hasNextInt()) {
int next = input.nextInt();
if (next >= 0 && next <= 12) {
...
}
}
Upvotes: 0