scanner calculates the average

We can enter multiple numbers, and find the sum and average value. Each number entered is confirmed with Enter, and the result is output by entering a non-number.

Create a scanner object to receive keyboard data
Scanner scanner = new Scanner(System.in);

        double sum = 0;
        int m = 0;      //计算输入了多少个数字

        //通过循环判断是否还有输入,并在里边对每一次进行求和统计
        while (scanner.hasNextDouble()) {
    
            //判断是否有下一个double类型的数据
            double x = scanner.nextDouble();    //有的话接收
            m++;
            sum += x;
            System.out.println("当前输入了" + m + "个数据,当前数据的和为" + sum);
            System.out.println("当前输入了" + m + "个数据,当前数据的平均值为" + sum / m);
        }
        System.out.println(m+"个数的和为:"+sum);
        System.out.println(m+"个数的平均值为:"+sum/m);

Close the program to save memory:
scanner.close();

Guess you like

Origin blog.csdn.net/qq_45361567/article/details/112639138