为什么 java 在我接受用户输入时显示异常?

Why is java showing me exception when i am taking input from the user?

public static void inputThenPrintSumAndAverage (){
        Scanner scanner = new Scanner(System.in);
        int count =0;
        int sum =0 ;
        long average = 0;
        boolean isAnInt = scanner.hasNextInt();
        while (true) {
            count++;
            int number = scanner.nextInt();
            if (isAnInt) {
                sum+=number;
                average = Math.round((sum/count));
            } else {
                break;
            }
            scanner.nextLine();
        }
        System.out.println("SUM = "+sum+ " AVG = "+average);
        scanner.close();
    }

当我给它一个字符串时,它给出了异常,甚至不执行“sum and avg”值。我怎样才能更改代码以使其工作?如果我有一些错误的概念知识,请帮助我理解这个概念。谢谢。

  1. Scanner(System.in) 不需要 Scanner#hasNextInt。此外,您不需要检查 if (isAnInt)。相反,你应该放一个 try-catch 块。
  2. 你不应该关闭 Scanner(System.in);否则的话,不重启JVM就无法再次打开了。

当您将 Scanner 用于 File 时,以上两项都是必需的。

演示:

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Test
        inputThenPrintSumAndAverage();
    }

    public static void inputThenPrintSumAndAverage() {
        Scanner scanner = new Scanner(System.in);
        int count = 0;
        int sum = 0;
        long average = 0;
        while (true) {
            try {
                int number = scanner.nextInt();
                sum += number;
                count++;
            } catch (InputMismatchException e) {
                break;
            }
        }
        average = Math.round((sum / count));
        System.out.println("SUM = " + sum + " AVG = " + average);
    }
}

样本运行:

2
3
5
8
abc
SUM = 18 AVG = 4

注意: 如果将平均值声明为 double 并将浮点计算存储到其中而不进行舍入,则可以获得更好的平均值精度,例如

import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        // Test
        inputThenPrintSumAndAverage();
    }

    public static void inputThenPrintSumAndAverage() {
        Scanner scanner = new Scanner(System.in);
        int count = 0;
        int sum = 0;
        double average = 0;
        while (true) {
            try {
                int number = scanner.nextInt();
                sum += number;
                count++;
            } catch (InputMismatchException e) {
                break;
            }
        }
        average = (double) sum / count;
        System.out.println("SUM = " + sum + " AVG = " + average);
    }
}

此更改后的示例 运行:

2
3
5
8
abc
SUM = 18 AVG = 4.5

对你理解this concept也很有用。