Validate Scanner input on a numeric range

前端 未结 2 913
故里飘歌
故里飘歌 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: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));
    

提交回复
热议问题