这是任务:
输入的示例输出:57 -2 98 13 85 77 999
这是我的解决方案:
import java.util.Scanner;
public class TestScoreStatistics {
public static void main(String[] args)
{
int max=0;
int min=999;
int avg=0;
int count=0;
int sum=0;
int num;
Scanner scan=new Scanner(System.in);
System.out.println("Please input test scores with values between 0-100.\nEnter 999 to finish.");
num=scan.nextInt();
int temp=num;
do
{
if(num==999)
System.exit(0);
if(num>=0 && num<=100)
{
count++;
sum+=num;
if(num>max )
max=num;
if(num<min)
min=num;
}
} while((num=scan.nextInt())!=999);
System.out.println("Test Statistics:");
System.out.println("Number of tests: "+count);
System.out.println("Lowest: "+min);
System.out.println("Highest: "+max);;
System.out.printf("Average: " + sum/count);
}
}
但输入为999时输出应为 测试统计: 测试次数:0 最低:0 最高:0 平均值:0 我该怎么做?
答案 0 :(得分:3)
这就是我要做的。如果它是你的编程类的分配,我建议用其他代码替换带有集合等的行(你可以在stackoverflow上找到它)
List<Integer> scores = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Please input test scores with values between 0-100. Enter 999 to finish.");
int num = scan.nextInt();
do {
if (num == 999)
break;
if (num >= 0 && num <= 100) {
scores.add(num);
}
}
while ((num = scan.nextInt()) != 999);
if (scores.size() != 0) {
System.out.println("Test Statistics:");
System.out.println("Number of tests: " + scores.size());
System.out.println("Lowest: " + scores.indexOf(Collections.min(scores)));
System.out.println("Highest: " + scores.indexOf(Collections.max(scores)));
System.out.printf("Average: " + scores.stream().mapToInt(Integer::intValue).sum() / scores.size());
} else {
System.out.println("Test Statistics:");
System.out.println("Number of tests: 0");
System.out.println("Lowest: 0 *or write whatever you want here");
System.out.println("Highest: 0");
System.out.printf("Average: 0");
}
答案 1 :(得分:0)
您可能需要考虑更改:
if(num==999)
System.exit(0);
为:
if(num==999)
break;
当您的第一个输入为“do-while
”时,它将导致退出999
循环,而不是完成程序。你需要解决的问题是在这里除以0:
System.out.printf("Average: " + sum/count);
您可以将其更改为:
if (count == 0) {
System.out.printf("Average: 0"); // Show average as 0 here, when count is equal to 0.
} else {
System.out.printf("Average: " + sum / count);
}
或类似的东西你需要执行而不是在那里除以。