这是我的任务:Java错误比较时,最大和最小的数字和金额与while循环
编写一个程序来读取非负整数列表和显示的最大整数,最小的整数,所有整数的平均值。用户 通过输入用于查找最大值,最小值和平均值的不是 的负哨值来指示输入结束。平均值应该是 是double
类型的值,因此它将使用小数部分进行计算。
我已经得到不同的部分使用不同的方法:方法A使最大和最小正确和总和错误,方法B使得总和和最大正确和最小错误。下面的代码演示方法B.一些变量注释掉:
public class testthis2
{
public static void main(String[] args) {
System.out.println("Enter Numbers of Nonnegative Integers.");
System.out.println("When complete, enter -1 to end input values.");
Scanner keyboard = new Scanner(System.in);
//int max = keyboard.nextInt();
int max = 0;
int min = max; //The max and min so far are the first score.
//int next = keyboard.nextInt();
int count = 0;
int sum = 0;
boolean areMore = true;
boolean run_it = false; //run it if its true
//if (max <= -1) {
// System.out.println("Thanks for playing!");
// run_it = false;
//}
// else
// run_it = true;
while(areMore) //always true
{
int next = keyboard.nextInt();
//int max = 0;
// min = max;
if (next < 0) { //if -1 is entered end loop.
areMore = false;
run_it = false;
break;
}
else //run this badboy
if(next >= max)
max = next;
else if(next <= min)
min = next;
run_it = true;
sum += next;
count++;
}
if (run_it = true)
System.out.println("The highest score is " + max);
System.out.println("The lowest score is " + min);
System.out.println("count " + count);
System.out.println("sum " + sum);
System.out.println("average " + (double)(sum/count));
System.out.println("Thanks for playing!");
}
}
当我运行这个测试,最大,求和,计数,平均是正确的。但是,最小值是错误的,因为显然没有输入0。下面是一个示例测试运行:
When complete, enter -1 to end input values.
37
25
30
20
11
14
-1
The highest score is 37
The lowest score is 0
count 6
sum 137
average 22.0
Thanks for playing!
任何帮助将不胜感激。谢谢!
你能否澄清究竟什么是实际的和预期的输出是/应该是什么? – nhgrif
所以我的测试输入是37,25,30,20,11,14,然后-1结束循环;它工作到目前为止,由于这里偷窥,但我有一个新的问题,我想测试只是输入-1,现在我输入-1当提示显示它仍然运行并计算一切,当它不假设。任何人都在意帮助我呢? – NikedunkSB