![](/img/trans.png)
[英]how to get the sum, average, minimum and maximum of five numbers-java using do-while loop
[英]Average Score Java using a Do While loop
我正在為學校分配作業,以根據給定的輸入計算平均考試成績。 當我輸入“ -1”時,它不會退出do / while循環。 當我插入一個值時,計數不會增加,因此平均值無法正確計算。
- 創建一個稱為平均值的類。
- 嘗試在main方法中使用單獨的部分來聲明所有變量,獲取輸入,進行處理以及執行輸出。 為每個部分創建一個注釋。
- 在main的聲明部分中,聲明一個稱為average的雙精度變量。
- 在main的輸入部分中,使用JOptionPane顯示打開消息,解釋該程序的用途。
- 在main的處理部分中,通過調用一個名為calcAverage()的方法來分配平均值。
- 在calcAverage方法中,聲明int變量count,score和total,以及一個稱為average的雙精度變量。
- 同樣在calcAverage方法中,使用do-while循環從用戶獲取分數,直到用戶輸入-1退出為止。 (您給用戶的消息應該是“輸入分數或-1退出”。)
- 在calcAverage方法中,計算平均得分並將該值返回給main方法。
- 在main的輸出部分中,顯示一個JOptionPane窗口,該窗口指出(例如)“ 5個分數的平均值為75.8”。
import javax.swing.JOptionPane;
public class Average {
static int count = 0;
public static void main(String[] args) {
//Declaration section
double average;
//Input Section
calcAverage();
//Processing Section
average = calcAverage();
//Output Section
JOptionPane.showMessageDialog(null, "The average of the " + count + "scores is" + average);
} // end main
public static double calcAverage() {
int count = 0, score = 0, total = 0;
double average;
String input;
do {
input = JOptionPane.showInputDialog("Enter a score or -1 to quit");
score = Integer.parseInt(input);
total = total + score;
count++;
} while (score != -1);
average = (total / count);
return average;
} // end calcAverage
} // end class
您在calcAverage
count
局部變量正在遮蓋您在Average
類中聲明為static
的count
變量,因此永遠不會更新static
變量; 它仍然為0。請勿在calcAverage
重新聲明此變量。
您兩次調用calcAverage
,而忽略了第一次返回的內容。 因此,您必須兩次輸入-1
才能完成程序。 刪除第一個calcAverage
調用。
即使輸入-1
,您也總是計算該數字,因為直到循環結束時才檢查條件。 添加一個if
條件以更新total
並僅在score
不為-1
count
。
您在這條線上有整數除法:
average = (total / count);
在Java中,整數除法產生一個整數,因此2個數字5和6的平均值為5,而不是5.5。 將其中之一double
。
average = ((double) total / count);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.