我正在嘗試處理Java任務。這是它要求的:這是使用IllegalArgumentException的正確方法嗎?
寫一個類
TestScores
。類構造函數應該接受一組測試分數作爲它的參數。該類應該有一個返回測試分數平均值的方法。如果陣列中的測試分數爲負數或大於100,則該班級應拋出IllegalArgumentException
。演示。我需要一個名爲TestScores
和TestScoresDemo
的文件。
這是我到目前爲止。我知道有一些是錯誤的,我需要幫助修復它:
class TestScores {
public static void checkscore(int s) {
if (s<0) throw new IllegalArgumentException("Error: score is negative.");
else if (s>100) throw new IllegalArgumentException("Error Score is higher then 100");
else if (s>89)throw new IllegalArgumentException("Your grade is an A");
else if (s>79 && s<90)throw new IllegalArgumentException("Your grade is an B");
else if (s>69 && s<80)throw new IllegalArgumentException("Your grade is an C");
else if (s>59 && s<70)throw new IllegalArgumentException("Your grade is an D");
else if (s<60)throw new IllegalArgumentException("Your grade is an F");
{
int sum = 0; //all elements together
for (int i = 0; i < a.length; i++)
sum += a[i];
}
return sum/a.length;
}
}
class TestScoresDemo {
public static void main(String[] args) {
int score = 0;
Scanner scanner = new Scanner(System.in);
System.out.print(" Enter a Grade number: ");
String input = scanner.nextLine();
score = Integer.parseInt(input);
TestScores.checkscore(score);
System.out.print("Test score average is" + sum);
}
}
我知道一個try
語句分配來電,因爲在我的書,這就是我與IllegalArgumentException
看到。誰能幫我?我使用Eclipse作爲IDE。
你爲什麼認爲這是錯的?你有錯誤信息,你不應該?如果我們不知道哪部分需要修復,我們無法提供幫助。 – 2012-04-27 03:00:57
謝謝。讓我仔細檢查並回復你。也許它只是一個簡單的類型錯誤 – Alexandria 2012-04-27 03:04:47
你應該只在拋出一個'IllegalArgumentException'的情況下,在你的情況下,參數無效0或大於100. – twain249 2012-04-27 03:05:03