Search code examples
javawhile-looptry-catchjava.util.scanner

Scanner outside Java while loop


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();
            }
        }
    }


}```

Solution

  • 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();
                }
            }
        }