import java.util.Scanner;
public class TestScoreApp { public static void main(String[] args) {
// initialize variables and create a Scanner object
int scoreTotal = 0;
int scoreCount = 0;
int testScore = 0;
String choice = "y";
Scanner sc = new Scanner(System.in);
// get a series of test scores from the user
while(choice.equalsIgnoreCase("y"))
{
System.out.println("How many testscores would you like to enter?");
int numberOfTestScores = sc.nextInt();
// display operational messages
System.out.println("Please enter test scores that range from 0 to 100.");
System.out.println(); // print a blank line
for(int i = 0; i == numberOfTestScores; i++)
{
// get the input from the user
System.out.print("Enter score " + numberOfTestScores + ": ");
testScore = sc.nextInt();
// accumulate score count and score total
if (testScore <= 100)
{
scoreCount = scoreCount + 1;
scoreTotal = scoreTotal + testScore;
}
else if (testScore > 100)
System.out.println("Invalid entry, not counted");
{
// display the score count, score total, and average score
double averageScore = scoreTotal / scoreCount;
String message = "\n" +
"Score count: " + scoreCount + "\n"
+ "Score total: " + scoreTotal + "\n"
+ "Average score: " + averageScore + "\n";
System.out.println(message);
}
System.out.println("Would you like to enter another set of scores? y/n");
sc.next(choice);
System.out.println();
}
}
}
}
上面的代码是让用户输入测试分数。他们首先选择了他们想要进入的人数。 for循环用于确保它们输入正确的数量。之后,输出得分,得分总数和平均得分的数量。我目前正在获得输出:
How many testscores would you like to enter?
34
Please enter test scores that range from 0 to 100.
How many testscores would you like to enter?
43
Please enter test scores that range from 0 to 100.
How many testscores would you like to enter?
3
Please enter test scores that range from 0 to 100.
How many testscores would you like to enter?
如果有人解释了不让while循环的控制转向for循环背后的逻辑错误,我将不胜感激。
答案 0 :(得分:2)
您没有获得任何测试分数,因为for
循环上的条件错误。它从一开始就是false
,只有条件为true
时,循环才会循环。变化
for(int i = 0; i == numberOfTestScores; i++)
到
for(int i = 0; i < numberOfTestScores; i++)