0

我正在编写一个程序来计算用户输入的平均值。

import java.util.Scanner;
public class mean
{   
    static Scanner input = new Scanner (System.in);
    public static void main (String[] args)
    {
    double i;
    double sum = 0;
    int count = 0;
    do
    {
        System.out.println("input");
        i = input.nextDouble();
        sum = sum + i;
        count++;
    }while (i != 0);
    System.out.println("sum is " + sum + " count is " + (count - 1));
    System.out.println("average is " + sum / (count - 1));
}
}

这里如果我输入0,它会计算。但如果列表中有 0。有人可以指导我一段时间吗?

4

2 回答 2

2

您可以询问扫描仪,扫描仪正在读取的下一个令牌是否是双重的,如果不是,则中断。下面的例子:

import java.util.Scanner;
public class mean
{   
    static Scanner input = new Scanner (System.in);
    public static void main (String[] args)
    {
    double i;
    double sum = 0;
    int count = 0;
    while(input.hasNextDouble())
    {
        System.out.println("input");
        i = input.nextDouble();
        sum = sum + i;
        count++;
    }
    System.out.println("sum is " + sum + " count is " + (count));
    System.out.println("average is " + sum / (count));
}
}

如果用户输入一个非数字字符(例如不是'+'、'-'、0-9、'.'等),循环将中断,因为input.hasNextDouble()将返回false。

于 2012-06-04T20:08:19.613 回答
0

而不是 sum = sum + i更简单的方法sum += i

于 2017-11-28T17:17:10.183 回答