Java中Scanner的进阶---求和与求平均数

求一组数字的和sum,求平均数sum/n

代码

package com.kuang.scanner;

import java.util.Scanner;

public class Demon05 {
    public static void main(String[] args) {
        //我们可以输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输入执行结果;
        Scanner scanner = new Scanner(System.in);   //创建一个扫描器的对象,用它接收键盘输入数据

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

        //通过循环判断是否还有输入,并且里面对每一次进行求和和统计
        while (scanner.hasNextDouble()){
            double x = scanner.nextDouble();
            m = m + 1; //m++
            sum = sum + x;
            System.out.println("你输入了第"+m+"个数据,当前结果sum="+sum);
        }

        System.out.println(m + "个数的和为" + sum);
        System.out.println(m + "个数的平均值是" + (sum / m));

        scanner.close();

    }
}

运行结果

D:\environment\java\jdk1.8\bin\java.exe "-javaagent:D:\IntelliJ IDEA 2020.3.2\lib\idea_rt.jar=51521:D:\IntelliJ IDEA 2020.3.2\bin" -Dfile.encoding=UTF-8 -classpath D:\environment\java\jdk1.8\jre\lib\charsets.jar;D:\environment\java\jdk1.8\jre\lib\deploy.jar;D:\environment\java\jdk1.8\jre\lib\ext\access-bridge-64.jar;D:\environment\java\jdk1.8\jre\lib\ext\cldrdata.jar;D:\environment\java\jdk1.8\jre\lib\ext\dnsns.jar;D:\environment\java\jdk1.8\jre\lib\ext\jaccess.jar;D:\environment\java\jdk1.8\jre\lib\ext\jfxrt.jar;D:\environment\java\jdk1.8\jre\lib\ext\localedata.jar;D:\environment\java\jdk1.8\jre\lib\ext\nashorn.jar;D:\environment\java\jdk1.8\jre\lib\ext\sunec.jar;D:\environment\java\jdk1.8\jre\lib\ext\sunjce_provider.jar;D:\environment\java\jdk1.8\jre\lib\ext\sunmscapi.jar;D:\environment\java\jdk1.8\jre\lib\ext\sunpkcs11.jar;D:\environment\java\jdk1.8\jre\lib\ext\zipfs.jar;D:\environment\java\jdk1.8\jre\lib\javaws.jar;D:\environment\java\jdk1.8\jre\lib\jce.jar;D:\environment\java\jdk1.8\jre\lib\jfr.jar;D:\environment\java\jdk1.8\jre\lib\jfxswt.jar;D:\environment\java\jdk1.8\jre\lib\jsse.jar;D:\environment\java\jdk1.8\jre\lib\management-agent.jar;D:\environment\java\jdk1.8\jre\lib\plugin.jar;D:\environment\java\jdk1.8\jre\lib\resources.jar;D:\environment\java\jdk1.8\jre\lib\rt.jar;E:\桌面\java学习\production\基础语法 com.kuang.scanner.Demon05
10
你输入了第1个数据,当前结果sum=10.0
20
你输入了第2个数据,当前结果sum=30.0
30
你输入了第3个数据,当前结果sum=60.03个数的和为60.0
3个数的平均值是20.0

Process finished with exit code 0

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页