2 回答

TA貢獻(xiàn)1765條經(jīng)驗(yàn) 獲得超5個(gè)贊
首先檢查分?jǐn)?shù)是否合法,然后增加計(jì)數(shù)器并將其添加到您的total. 您還可以分配score和檢查不是-1通過單個(gè)操作。并且始終使用大括號(hào)(即使它們是可選的)。喜歡,
// 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貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
試試這個(gè)代碼。這個(gè)對(duì)我有用:
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
}
添加回答
舉報(bào)