【发布时间】:2019-10-03 17:45:26
【问题描述】:
此代码要求的分数在 0-100 之间。如果分数介于两者之间,则将其添加到总分中,然后用于计算平均值。我遇到的问题是如果分数大于 100 则放置 if 语句,打印非法语句并要求用户重新输入数字。当我把这个 if 放在 while 循环中时,我会打印出无限数量的非法异常。我该如何解决这个问题?
public class SentinalValuedControlledLoop {
public static void main(String[] args) {
int studentCount = 1;
double total = 0.0;
double average;
int score;
Scanner stdin = new Scanner(System.in);
//title at top of output
System.out.println("Sai Bharathula's Score Report");
//read score for student
System.out.printf("Enter a score (0 too 100, -1 to quit #%d:)", studentCount);
score = stdin.nextInt();
while(score !=-1) {
//THIS IS THE IF STATEMENT I AM TALKING ABOUT THAT IS CAUSING ME TROUBLE
if(score >100){
System.out.println("Illegal Score Try Again");
}
if(score >0 && score <= 100) {
System.out.printf ("Enter a score (0 too 100, -1 to quit #%d:)", studentCount);
score = stdin.nextInt();
studentCount++;
}
}
average = total / studentCount;
System.out.printf ("\nThe average score for %d students is %8.2f\n",
studentCount, average);
}
}
【问题讨论】:
-
如果输入的数字大于100,则需要从用户那里获取一个新的数字。你没有这样做,所以
score永远保持在那个初始值,让你的代码陷入无限循环。
标签: java if-statement