我正在编写一个程序来计算用户输入的平均值。
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。有人可以指导我很好的条件吗?
答案 0 :(得分: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。 / p>
答案 1 :(得分:0)
而不是sum = sum + i
更简单的方法是sum += i