简体   繁体   中英

Java User Input - Enter integer within certain range or loop back and try again

I have to build a user input template where you can enter a number between 100 and 200. If you type "goodbye", it needs to exit, if you enter a letter, symbol, number outside the range, etc. it needs to prompt you to try again. if you enter a number within the range, it will move on to another question (I haven't included that in the code below).

I got almost everything to work. If you enter a correct number the first time, it works. The "goodbye" and wrong character functions also work. BUT if you enter the wrong character (number or letter) and then, when it prompts you to try again, you put a CORRECT number in the range, it does not accept it and again prompts you to try again.

I need to figure out how to input a wrong character (such as a letter or number outside of range), and then when it prompts you to try again and you put a number between 100-200, it works and exits the loop (which will enable it to go on to the next question/loop).

Here is my code:

Scanner console = new Scanner(System.in);
    String Input;
    int Number;
    boolean isValid = true;        
        do {
        System.out.println("Enter a valid number:");
        Input = console.nextLine();
           if (Input.equals("goodbye") || Input.equals("GOODBYE")){
               System.out.println("You have left");
              System.exit(0);
           }
        char[] numberTester = Input.toCharArray();
       for (int i = 0; i<Input.length(); i++){
           Character currentChar = new Character (numberTester[i]);
           if (!currentChar.isDigit(numberTester[i])){
             isValid = false;
             System.out.println("Invalid. Try again.");
              i = Input.length();
           }
           if (isValid == true){
           Number = Integer.parseInt(Input);    
           if (Number < 100 || Number > 200){
             isValid = false;
             System.out.println("Invalid. Try again.");
               }
           }
       } 
        } while (isValid == false);
}
        }

In the beginning your isValid flag is set true . Your do-while loop runs while this flag is false . If you enter something valid in your first round it quits the loop. But if you enter something invalid you set your flag to false and never back again, so it loops forever.
Setting your isValid flag true as first statement in your do while loop should solve your problem.

[...]
do{
    isValid = true;
    [...]
} while (isValid == false);

I think the purpose of this assignment is to learn how to handle exceptions. parseInt will throw a NumberFormatException . Use this to your advantage instead of that toCharArray nonsense.

public static void main(String args[]) {

    Scanner console = new Scanner(System.in);
    String input;
    int number;
    boolean isValid;

    do {
        isValid = true; // reset the validity
        System.out.print("Enter a valid number: ");
        input = console.nextLine();
        if (input.equalsIgnoreCase("goodbye")) {
            System.out.println("You have left");
            System.exit(0);
        }

        try {
            number = Integer.parseInt(input);
            if (number < 100 || number > 200) {
                isValid = false;
                System.out.println("Invalid. Try again.");
            }
        } catch (NumberFormatException e) {
            isValid = false;
            System.out.println("Invalid. Not a number. Try again.");
        }

    } while (!isValid);
}

It looks like the issue is coming from the fact that once you set the isValid variable to false, it never becomes true, so the do-while loop will loop infinitely.

One way to fix this would be to to set the isValid variable to true at the beginning of each cycle of the do-while loop, so that if nothing triggers it to become false within the loop, the loop will be exited at the end since the condition will not be true.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM