如何计算所有输入的整数而不计算0?
我想要的是如果用户输入0然后输出将是"除了0"之外没有输入任何数字,但由于我有其他输出它也将打印出来。
Scanner input = new Scanner(System.in);
System.out.print("Enter integers, input ends with 0: ");
int number = input.nextInt();
if(number==0){ //This prints out along with the other system.out.println
System.out.println("No numbers were entered except 0");
}
while(number!=0){
count++;
total += number;
if(number > 0){
positive++;
}
else{
negative++;
}
number = input.nextInt();
}
average = total*1.0/count;
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total count is " + total);
System.out.printf("The average is " + average);
}
}
OUTPUT:
Enter integers, input ends with 0: 1 2 -1 3 0
The number of positives is 3
The number of negatives is 1
The total count is 4 //mine is reading out 5 entered integers instead of 4
The average is 1.25`
//0 is the only entered number
Enter integers, input ends with 0: 0
No numbers were entered except 0
答案 0 :(得分:0)
您似乎期待与您所要求的不同的东西:
The total count is 4
这反映了您输入的值的总和,而不是值的数量
使用System.out.println("The total count is " + count);
可以获得值的数量(计数)。
要在未输入数字(0除外)时删除额外输出,请更改以下代码:
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total count is " + total);
System.out.printf("The average is " + average);
到
if (count > 0)
{
System.out.println("The number of positives is " + positive);
System.out.println("The number of negatives is " + negative);
System.out.println("The total count is " + total);
System.out.printf("The average is " + average);
}