Java ArrayList的平均/最大值
我在这个程序中遇到了很多问题,添加了一个while hasnetint,还有很多其他的东西,我终于让代码正常工作了,但是我的输出只是第一个输入,而不是输入的max/avg。有人能告诉我我把事情搞砸了吗Java ArrayList的平均/最大值,java,Java,我在这个程序中遇到了很多问题,添加了一个while hasnetint,还有很多其他的东西,我终于让代码正常工作了,但是我的输出只是第一个输入,而不是输入的max/avg。有人能告诉我我把事情搞砸了吗 public class LabProgram { public static void main(String[] args) { Scanner scnr = new Scanner(System.in); int count = 0, max = 0,
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
int num = scnr.nextInt();
if (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
num = scnr.nextInt();
}
int avg = count == 0 ? 0 : total/count;
System.out.println(avg + " " + max);
}
}
您没有使用循环从控制台获取数字。此外,avg的逻辑可能导致错误答案。找到下面的解决方案
Scanner scnr = new Scanner(System.in);
int count = 0, max = 0, total = 0;
System.out.println("Enter any other characters expect numbers to terminate:");
while(scnr.hasNextInt()) {
int num = scnr.nextInt();
if (num >= 0) {
count++;
total += num;
max = Math.max(max, num);
}
}
double avg = count == 0 ? 0 : (double)total/(double)count; // to print correct avg
System.out.println(avg + " " + max);
样本输出:
Enter any other characters expect numbers to terminate:
3
3
34
a
13.333333333333334 34
由于缺少读取元素的循环,因此需要执行
num=scnr.nextInt()
在使用max
计算中的num
值之前,您的avg
将是错误的,因为OP最好也测试除以零。