How to type a string to end a integer Scanning process in Java

前端 未结 3 403
闹比i
闹比i 2021-01-27 03:21

I would like to use Scanner to scan any number of integer then get the average. Before I stop, I would like to type \"END\".

The code below has: Exception in

3条回答
  •  盖世英雄少女心
    2021-01-27 03:53

    You could just scan the whole line and check if the line is a number like this

    public static int scanaverage() {
        System.out.println("Enter any number, type 'END' to exit");
        Scanner input = new Scanner(System.in);
        int total = 0;
        int count = 0;
        String line;
        do {
            line = input.nextLine();
            try {
                total += Integer.parseInt(line); // Cast the number, if it does not succeed catch the exception.
                count += 1;
            } catch(NumberFormatException e) {
                if(!line.equalsIgnoreCase("end")) { // Wrong input
                    System.out.println("Wrong input, input another number or end");
                }
            }
        } while (!line.equalsIgnoreCase("end"));
        return total / count;
    }
    

提交回复
热议问题