0

I'm creating a method that makes the user choose what he wants to do through 2 choices associated with numbers. In case the user inserts any string in input, my code prints infinite:

Choose an optionError
1 - New game
2 - Load game

In all other cases the code works correctly, so i think the error is in the catch(). I tried closing the Scanner object with instructions in some parts of the code but the problem persists.

If instead I declare the Scanner object inside the while loop in the Start() method, the code works perfectly. I can't figure out how the scanner object works and why I have this problem.

import java.util.Scanner;

public class Metods {

    static Scanner input = new Scanner(System.in);

    public static int Start() {
        while(true) {
            
            int choice;
    
            System.out.println("1 - New game");
            System.out.println("2 - Load game");
            System.out.print("\nChoose an option");
    
            try {
                choice = input.nextInt();
                //input.close();
            } catch (Exception e) {
                System.out.println("Error");
                //input.close();
                continue;
            }

            if (choice == 1 || choice == 2) {
                //input.close();
                return choice;
            }
            else {
                System.out.println("Error");
                //input.close();
            }
        }
    }


}```
1
  • You never break out of the infinite loop. Commented Jan 7, 2023 at 18:13

2 Answers 2

1

In every loop circle you are trying to parse the input again. The nextInt() methods throws an exception, but the input is still not processed and so the next loop circle tries again to parse the input...

You should read the input as String, check if it's a valid option (1 or 2) and return the option as integer (if you need it) otherwise the loop will start again waiting for new input because your input was porcessed.

I just changed the relevant parts.

 public static int start() {
        while(true) {

            String choice;

            System.out.println("1 - New game");
            System.out.println("2 - Load game");
            System.out.print("\nChoose an option");

            try {
                choice = input.next();
                //input.close();
            } catch (Exception e) {
                System.out.println("Error");
                //input.close();
                continue;
            }

            if (choice.equals("1") || choice.equals("2")){
                //input.close();
                return Integer.parseInt(choice);
            }
            else {
                System.out.println("Error");
                //input.close();
            }
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

Because the data read by nextInt is not an integer, but the data is not automatically skipped .

You can skip wrong characters with input.next() method

    static Scanner input = new Scanner(System.in);

    public static int Start() {
        while(true) {
            int choice;
    
            System.out.println("1 - New game");
            System.out.println("2 - Load game");
            System.out.print("\nChoose an option");
    
            try {
                choice = input.nextInt();
                //input.close();
            } catch (Exception e) {
                System.out.println("Error");
                if( input.hasNext() ) {
                    input.next();
                }
                //input.close();
                continue;
            }

            if (choice == 1 || choice == 2) {
                //input.close();
                return choice;
            }
            else {
                System.out.println("Error");
                //input.close();
            }
        }
    }

2 Comments

Thanks, that helped, but I don't understand why the Scanner behaves like this. So if I undestood, in case of an exception the scanner keeps the previously read input in memory and in case of a new next() or nextLine() instruction, the scanner reads this which was saved and the user has no possibility to enter anything else, right?
Thats right, like I said in my answer the input isn't processed and 'sticks' in the Scanner. You can handle the 'wrong' input in the catch clause e. g. for logging which input raised the exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.