Home > Software engineering >  Scanner outside Java while loop
Scanner outside Java while loop

Time:01-08

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


}```

CodePudding user response:

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

CodePudding user response:

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