简体   繁体   中英

Why is my While Loop wont loop my Catch, like my if else statement?

I am trying to make a program where the user will input a random integer/number. But the main issue is, if users accidentally input a String, I want them to be informed and also I want them to ask to input again by asking them again. But in my code, I cant loop my catch.

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int answer = 28;
    int attempts = 0;
    
    System.out.println("Guess a Number 1 - 50:");
    
    while(true) {
      try {
        int input = scan.nextInt();
        scan.nextLine();
        if(input > answer) {
          System.out.println("Too Big");
          System.out.println("Guess a Number 1 - 50:");
        } else if (input < answer) {
          System.out.println("Too Small");
          System.out.println("Guess a Number 1 - 50:");
        } else if (input == answer ) {
          System.out.println("Congrats!");
        } 
      } catch (InputMismatchException e) {
        System.out.println("Numbers only");
        System.out.println("Guess a Number 1 - 50:");
      } 
    }
}

Try-catch block stops the execution of the while loop when it throws an error (when you had a catch). You can use another if-else statement to check if it was a number instead of a try-catch block.

public static boolean isNumeric(String string) {
    int intValue;
        
    System.out.println(String.format("Parsing string: \"%s\"", string));
        
    if(string == null || string.equals("")) {
        System.out.println("String cannot be parsed, it is null or empty.");
        return false;
    }
    
    try {
        intValue = Integer.parseInt(string);
        return true;
    } catch (NumberFormatException e) {
        System.out.println("Input String cannot be parsed to Integer.");
    }
    return false;
}

you can use a helper method like this to return true or false in your if statement.

check this URL for more information.

ps : This is only one method of implementation. I think you will be able to work around with some solution with try-catch also. You can try implementing inputting user input again inside the catch block to repeat the process.

Remove the scan.nextLine(); from your try block and then place a scan.skip(".*"); in your catch block. This will skip the invalid input ( .* matches basically any character). Additionally, you may replace the last else if with a simple else since that is the only possibility left. Having said that, try the following:

public static void main(String[] args) throws IOException {
    Scanner scan = new Scanner(System.in);

    int answer = 28;
    int attempts = 0;

    System.out.println("Guess a Number 1 - 50:");

    while(true) {
        try {
            int input = scan.nextInt();
            if(input > answer) {
                System.out.println("Too Big");
                System.out.println("Guess a Number 1 - 50:");
            } else if (input < answer) {
                System.out.println("Too Small");
                System.out.println("Guess a Number 1 - 50:");
            } else {
                System.out.println("Congrats!");
            }
        } catch (InputMismatchException e) {
            System.out.println("Numbers only");
            System.out.println("Guess a Number 1 - 50:");
            scan.skip(".*");
        }
    }
}

You are asking for a reason

This code has an infinite loop when invalid input is encountered because nextInt() does not take invalid tokens, So the invalid token stay there in the scanner because it is not consumed due to the exception, keep causing an exception to be thrown the next time you try to read an int because nextLine is never reached due to the exception.

This can be solved by putting the nextLine() inside the catch block to consume whatever input was causing the exception to be thrown, clearing the input stream and allowing the user to input something again.

    public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int answer = 28;
    int attempts = 0;
    
    System.out.println("Guess a Number 1 - 50:");
    
    while(true) {
      try {          
        int input = scan.nextInt();
        scan.nextLine();  // never reached when exception is thrown
        if(input > answer) {
          System.out.println("Too Big");
          System.out.println("Guess a Number 1 - 50:");
        } else if (input < answer) {
          System.out.println("Too Small");
          System.out.println("Guess a Number 1 - 50:");
        } else if (input == answer ) {
          System.out.println("Congrats!");
        } 
      } catch (InputMismatchException e) {
        scan.nextLine(); // This skips the invalid token 
        System.out.println("Numbers only");
        System.out.println("GuessNumber 1 - 50:");
      } 
    }
}

You should try this code, It will work perfectly for your requirement...


     public static void main(String[] args) {
        int answer = 28;
        System.out.println("Guess a Number 1 - 50:");
        boolean condition = true;
        while (condition) {
            try {
                    Scanner scan = new Scanner(System.in);
                    int input = scan.nextInt();
                    scan.nextLine();
                    if (input > answer) {
                        System.out.println("Too Big");
                        System.out.println("Guess a Number 1 - 50:");
                    } else if (input < answer) {
                        System.out.println("Too Small");
                        System.out.println("Guess a Number 1 - 50:");
                    } else {
                        System.out.println("Congrats!");
                        condition=false;
                    }
            } catch (Exception e) {
                    System.out.println("Numbers only");
                    System.out.println("Guess a Number 1 - 50:");
            }
        }
    }

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