Validate Scanner input on a numeric range

前端 未结 2 914
故里飘歌
故里飘歌 2021-01-16 12:55

I\'m currently creating my first game which is executed in a console.

I\'ve been asked to validate an input which can be done with a simple code. The goal is to inpu

相关标签:
2条回答
  • 2021-01-16 13:27

    Because you instantiate input to be 0, but never give the user an opportunity to change this, the conditions for the first two conditionals are always false (nothing is read from the Scanner and 0 is not between min and max). Therefore, the program falls through to the else every time. Just add a statement before the do-while that will obtain a value for input from the user.

    input = scanner.nextInt();
    
    // your do-while loop
    

    (You'll also probably have to adjust the code slightly to get the type of interaction you're looking for. Hint - you're reading two values from the user.)

    0 讨论(0)
  • 2021-01-16 13:31

    As Clint said the problem was in your input. Here's a demo how you can fix this,

    try (Scanner scanner = new Scanner(System.in)) {
    
                int input = 0;
                int min = 1;
                int max = 4;
    
                boolean inputValidate = false;
    
                System.out.println("Main Menu");
                System.out.println("=========");
                System.out.println("1. Play Game");
                System.out.println("2. About");
                System.out.println("3. View Saved Games");
                System.out.println("4. Exit");
                System.out.println("");
    
                do {
                    System.out.print(">> ");
    
                    try {
                        input = scanner.nextInt();
                        if (input >= min && input <= max) {
                            inputValidate = true;
                        } else {
                            System.out
                                    .println("Not in range. Please input number 1-4.");
                            scanner.nextLine();
                        }
                    } catch (InputMismatchException exception) {
                        System.out
                                .println("Not a number. Please input number 1-4.");
                        scanner.nextLine();
                    }
    
                } while (!(inputValidate));
    
    0 讨论(0)
提交回复
热议问题