Scanner续

Scanner续

一道基础题:输入多个数字,求数字的总和与平均数,通过非数字来结束输入,打印输出结果。

以下代码结合了Scanner和循环语句来解决它:

package com.cxf.scanner;

import java.util.Scanner;

public class Demo5 {
    public static void main(String[] args) {
        Scanner scanner1 = new Scanner(System.in);
        double sum = 0;
        double input = 0;
        int times = 0;
        System.out.println("please input:");
        while(scanner1.hasNextDouble()) {
            System.out.println("your next input:");
            input = scanner1.nextDouble();
            sum += input;
            times++;
        }
        System.out.println("the sum = "+ sum);
        if(times != 0) {
            System.out.println("the average = "+ sum/times);
        }
        scanner1.close();
    }
}

输入及输出结果:

please input:
10
your next input:
20
your next input:
30
your next input:
40
your next input:
d
the sum = 100.0
the average = 25.0
posted on 2021-08-16 18:01  菜小疯  阅读(23)  评论(0编辑  收藏  举报