2 回答
TA贡献1765条经验 获得超5个赞
首先检查分数是否合法,然后增加计数器并将其添加到您的total. 您还可以分配score和检查不是-1通过单个操作。并且始终使用大括号(即使它们是可选的)。喜欢,
// read the first score
System.out.printf("Enter a score (1-100, -1 to quit)" + ": ", scoreCount);
while ((score = stdin.nextDouble()) != -1.0) {
if (score < -1 || score > 100) {
System.out.println("Illegal score. Try again");
} else {
scoreCount++;
total += score;
}
System.out.printf("Enter a score (1-100, -1 to quit)" + ": ", scoreCount);
}
TA贡献1789条经验 获得超10个赞
试试这个代码。这个对我有用:
public class StudentSentinel {
public static void main(String[] args) {
double score;
double total = 0.0;
double average;
int scoreCount = 0;
// create the Scanner object. Name it stdin
Scanner stdin = new Scanner(System.in);
// title at the top of the output
System.out.println(" student score report");;
// read the first score
System.out.printf("Enter a score (1-100, -1 to quit)" +
": ", scoreCount);
score = stdin.nextDouble();
scoreCount++;
total += score;
while (score != -1.0) {
System.out.printf("Enter a score (1-100, -1 to quit)" +
": ", scoreCount);
scoreCount++;
score = stdin.nextDouble();
if (score < -1) {
System.out.println("Illegal score. Try again");
continue;
}else if (score > 100) {
System.out.println("Illegal score. Try again");
continue;
}
total += score;
// increment the loop counter
}
// end of for loop
average = total / scoreCount;
System.out.printf("\nThe average score for %d students is %8.2f\n",
scoreCount, average);
} // end of main
}
添加回答
举报