mango
mango

Reputation: 3

How to accept user input of a whole number within a range

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

Answers (2)

WJS
WJS

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.

  1. Prompt for the value.
  2. Read in the value.
  3. Verify the value is correct.
  4. If correct, proceed on with the program.
  5. Repeat starting at (1).

Upvotes: 1

Piotr Wilkin
Piotr Wilkin

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:

  • check if there is a number
  • read that number
  • check if the number passes the proper tests

In other words, something like:

if (input.hasNextInt()) {
 int next = input.nextInt();
 if (next >= 0 && next <= 12) {
  ...
 }
}

Upvotes: 0

Related Questions