我應該編寫一個程序,根據要輸入的主題數計算學生的平均成績。java計算等級中的程序
這裏是我的代碼,但它不進入年級的部分執行上subject1:
import javax.swing.*;
public class Arrays {
static int ctr = 0;
public static void main(String[] args) {
String inputStr = "";
double num2process = 0.0;
double sum = 0.0, ave = 0.0;
double[] grade = new double[(int) num2process];
while (true) {
try {
inputStr = JOptionPane.showInputDialog(
"Enter number of subjects to enter: ");
num2process = Double.parseDouble(inputStr);
while (ctr < num2process) {
grade[ctr] = getNumber();
sum += grade[ctr];
ctr++;
}
} catch (NumberFormatException err) {
JOptionPane.showMessageDialog(
null,
"There is an error on entry",
"Error Message", JOptionPane.WARNING_MESSAGE);
continue;
}
break;
}
// Accumulate the output.
String output = "";
int ctr2 = 0;
output = "";
while (ctr2 > num2process) {
output += ("Grade on subject " + (ctr2+1)
+ " is " + grade[ctr]);
ctr2++;
}
ave = sum/num2process;
output += "\nAverage is " + ave;
// Display the output.
JOptionPane.showMessageDialog(
null,
output,
"The result is",
JOptionPane.INFORMATION_MESSAGE);
}
public static int getNumber() throws NumberFormatException {
String inputStr = "";
int num = 0;
try {
inputStr = JOptionPane.showInputDialog(
"Enter grade on subject " + (ctr+1));
num = Integer.parseInt(inputStr);
return num;
} catch (NumberFormatException errorAgain) {
throw errorAgain;
}
}
}
請幫我解決這個錯誤感謝
關於'「但它並沒有在subject1進入年級的部分執行:」' - 你可以詳細一點?你的問題到底是什麼? –
爲什麼'getNumber()'拋出*和*捕獲'NumberFormatException'? –
此外,主方法內catch塊中的「continue」關鍵字不會執行任何操作。我認爲你需要從基礎開始。 –