英文:
How to not use a user input if it's invalid?
问题
import java.util.*;
public class QuizScoreStatistics {
public static void main(String args[]) {
float max = 0;
float min = 99;
float avg = 0;
float count = 0;
float sum = 0;
float num;
Scanner scan = new Scanner(System.in);
System.out.println("请输入0到10之间的测试分数。\n输入99结束输入。");
num = scan.nextInt();
float temp = num;
do {
if (num == 99)
System.exit(0);
if (num <= 0 || num > 10)
System.out.println("分数必须在0和10之间。");
if (num >= 0 && num <= 100) {
count++;
sum += num;
if (num > max)
max = num;
if (num < min)
min = num;
}
} while ((num = scan.nextInt()) != 99);
System.out.println("测试统计:");
System.out.println("测试数量:" + count);
System.out.println("最低分:" + min);
System.out.println("最高分:" + max);
System.out.printf("平均分:" + sum / count);
}
}
英文:
My program asks a user for test scores and displays the min/max, # of tests, and the average. However, if the score isn't between 0 and 10 I don't want that number used in my calculations. How would I go about doing that in my do/while loop? I've tried entering
System.exit(0); after line if (num <= 0 || num >10)
System.out.println("Score must be between 10 and 0");
but it breaks my program.
Here is my code:
import java.util.*;
public class QuizScoreStatistics {
public static void main (String args[]) {
float max=0;
float min=99;
float avg=0;
float count=0;
float sum=0;
float num;
Scanner scan=new Scanner(System.in);
System.out.println("Please input test scores with values between 0-10.\nEnter 99 to finish.");
num=scan.nextInt();
float temp=num;
do
{
if(num==99)
System.exit(0);
if (num <= 0 || num >10)
System.out.println("Score must be between 10 and 0");
if(num>=0 && num<=100)
{
count++;
sum+=num;
if(num>max )
max=num;
if(num<min)
min=num;
}
} while((num=scan.nextInt())!=99);
// 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);
}
}
答案1
得分: 3
你可以尝试继续执行do-while循环的其余部分。
if (num <= 0 || num > 10){
System.out.println("分数必须在0到10之间");
continue;
}
英文:
You can try continuing the rest of the do-while loop.
if (num <= 0 || num >10){
System.out.println("Score must be between 10 and 0");
continue;
}
答案2
得分: 0
做一个继续
如果(num <= 0 || num > 10){
系统。打印("错误答案");
num = scan.nextInt();
继续;
}
继续将跳到循环的下一次迭代。
所以你重新开始循环。
英文:
Do a continue
if(num <= 0 || num > 10){
System.out.println("wrong asnwer");
num = scan.nextInt();
continue;
}
continue will skip to the next iteration of the loop.
So you start the loop over.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论