0

I am working on a project (a game) and one of the requirements is to have warnings if they enter an option outside of the range (1-8) and if they enter a character. If the user enters an invalid number, the menu appears and asks them again which option they would like. If they enter a character, the program should ask them to enter an integer and ask for input again. This is what I have so far. It correctly identifies a number out of range and recalls the menu. It also identifies a character (invalid input), but does open input for the user to enter a correct option. How can I check both conditions?

Thanks, Tyler

            int userChoice = scnr.nextInt();//<-- use this variable
            if (userChoice.hasNextInt() == false)
            {
                System.out.println("Error: Menu selection must be an integer! Please try again:");
            }
            // Variable used for storing what the user's main menu choice
            if (0 > userChoice || userChoice > 8)
            {
                System.out.println("Error: Invalid Menu Selection.");
                System.out.println("");
                System.out.println("Available Actions:");
                System.out.println("(1) Print Market Prices");
                System.out.println("(2) Print Detailed Statistics");
                System.out.println("(3) Buy Some Sheep");
                System.out.println("(4) Buy a Guard Dog");
                System.out.println("(5) Sell a Sheep");
                System.out.println("(6) Sell a Guard Dog");
                System.out.println("(7) Enter Night Phase");
                System.out.println("(8) Quit");
                System.out.println("What would you like to do?");
                userChoice = scnr.nextInt();
            }
Tyler Waite
  • 9
  • 1
  • 1
  • 2

5 Answers5

0

you are using the hasNextInt() method on primitive int to see if the input is interger. instead use this:

int userChoice ;
        try{
        userChoice =scnr.nextInt();//<-- use this variable
        }
        catch(InputMismatchException ime){
            System.out.println("Error: Menu selection must be an integer! Please try again:");
        }

likewise use the same logic inside the if condition also

Balaji Krishnan
  • 967
  • 3
  • 11
  • 28
  • I don't think I can use those methods since this is an introductory project. Is there no simpler solution? – Tyler Waite Oct 02 '13 at 03:43
  • i have not used any additionl methods.. you had the hasNextInt() on a primitive which would not allow the code to compile. I have a the try catch block. If you feel that this is huge for introductory proj, you can use userChoice =scnr.nextInt(); without the surrounding try, catch block. but be warned that you will run into exceptions at runtime if the input is not an integer – Balaji Krishnan Oct 02 '13 at 03:48
0

Better to go with Switch-Case statement within a loop. Java JDK 1.7 also supports 'string' in switch-case now.

Yasa
  • 224
  • 4
  • 21
0
try{
   int userChoice = scnr.nextInt();
   if(userChoice > 0 && userChoice <9){
       // your logic
   }else{
       System.out.println("Invalid choice");
       showMenu();
   }

}catch(Exception e){
   System.out.println("Invalid choice");
   showMenu();
}

public void showMenu(){
     System.out.println("Available Actions:");
     System.out.println("(1) Print Market Prices");
     System.out.println("(2) Print Detailed Statistics");
     System.out.println("(3) Buy Some Sheep");
     System.out.println("(4) Buy a Guard Dog");
     System.out.println("(5) Sell a Sheep");
     System.out.println("(6) Sell a Guard Dog");
     System.out.println("(7) Enter Night Phase");
     System.out.println("(8) Quit");
     System.out.println("What would you like to do?");
}
0

First of all there is correction to be made on the sequence nextInt() and hasNextInt() is invoked. First one is used to read the value from input, and second is used to see whether the value type is int. So you have to invoke hasNext[Type]() followed by `next[Type].

Secondly, since nextInt() is returning an int, so it is incorrect to invoke hasNextInt() on the userChoice variable.

Let's correct those two first as below.

if (scnr.hasNextInt()) {
    int userChoice =  scnr.nextInt();
} else {
    // input is not an int
}

Now let's correct your code to get a valid int, also to print the instructions and ask for the input again for invalid inputs.

Scanner scnr = new Scanner(System.in);

boolean incorrectInput = true;
int userChoice = -1;

while (incorrectInput) {

    if (scnr.hasNextInt()) {

        userChoice = scnr.nextInt();
        // Variable used for storing what the user's main menu choice

        if (0 >= userChoice || userChoice > 8) {
            System.out.println("Error: Invalid Menu Selection.");
            System.out.println("");
            System.out.println("Available Actions:");
            System.out.println("(1) Print Market Prices");
            System.out.println("(2) Print Detailed Statistics");
            System.out.println("(3) Buy Some Sheep");
            System.out.println("(4) Buy a Guard Dog");
            System.out.println("(5) Sell a Sheep");
            System.out.println("(6) Sell a Guard Dog");
            System.out.println("(7) Enter Night Phase");
            System.out.println("(8) Quit");
            System.out.println("What would you like to do?");

        } else {
            incorrectInput = false;
        }
    } else {
        scnr.next();
        System.out.println("Error: Menu selection must be an integer! Please try again:");
    }
}
System.out.println("userChoice = " + userChoice);
lkamal
  • 3,160
  • 14
  • 28
0

Or, you can use the powerful IntegerValidator from Apache Commons Validator:

if (new IntegerValidator().isInRange(Integer value, int min, int max)) {
    // value is in range ...
}
yglodt
  • 11,334
  • 13
  • 74
  • 114