我試圖為我的 TestScores 類創建一個物件陣列,該類接受一個陣列,然后可以使用 averageScore 方法來獲得平均分數。然而,它似乎只寫入物件陣列的最后一個值,因為輸出只是列印輸入的最后一個值。我嘗試在填充它的 for 回圈中使用系統列印行來獲取物件陣列輸出,這似乎作業正常,但在回圈之外它似乎沒有給出預期的輸出,這將是平均值輸入到類中的每個陣列。
import java.io.*;
import java.util.Scanner;
public class TestScores implements Serializable{
private int[] testArray;
public TestScores(int[] parameter)
throws InvalidTestScore {
testArray = parameter;
for (int k : testArray) {
if (k > 100 || k < 0) {
throw new InvalidTestScore(k);
}
}
}
public int averageScore() {
int sum = 0;
for (int j : testArray) {
sum = j;
}
return sum / testArray.length;
}
public static void main(String[] args) throws InvalidTestScore, IOException, ClassNotFoundException {
int input;
int[] array = new int[2];
Scanner keyboard = new Scanner(System.in);
TestScores[] testScores = new TestScores[5];
for(int k = 0; k < testScores.length; k ) {
for (int i = 0; i < 2; i ) {
System.out.print("Enter a score: ");
input = keyboard.nextInt();
array[i] = input;
}
System.out.println("Array created ");
testScores[k] = new TestScores(array);
}
FileOutputStream outStream =
new FileOutputStream("Object.dat");
ObjectOutputStream objectOutputFile =
new ObjectOutputStream(outStream);
for (TestScores testScore : testScores) {
objectOutputFile.writeObject(testScore);
}
objectOutputFile.close();
System.out.println("Objects serialized and written to objects.dat");
FileInputStream inStream =
new FileInputStream("Object.dat");
ObjectInputStream objectInputFile =
new ObjectInputStream(inStream);
TestScores[] scores2 =
new TestScores[5];
for(int m = 0; m < scores2.length; m ){
scores2[m] =
(TestScores)objectInputFile.readObject();
}
objectInputFile.close();
for(int n = 0; n < 5; n ){
System.out.println("Average score " scores2[n].averageScore());
}
}
}
根據評論,我更改了代碼,而是將其設為陣列陣列,因此我沒有對整個程式使用相同的陣列。
public static void main(String[] args) throws InvalidTestScore,
IOException, ClassNotFoundException {
int input;
int[][] array = new int[5][2];
Scanner keyboard = new Scanner(System.in);
TestScores[] testScores = new TestScores[5];
for(int k = 0; k < testScores.length; k ) {
for (int i = 0; i < 2; i ) {
System.out.print("Enter a score: ");
input = keyboard.nextInt();
array[k][i] = input;
}
System.out.println("Array created ");
testScores[k] = new TestScores(array[k]);
}
uj5u.com熱心網友回復:
您將相同array的輸入資料添加到所有TestScore物件。因此,如果您array為實體的后續實體進行TestScore修改,您也會修改所有先前創建的實體。
有兩種可能的解決方案對我有用,請選擇更適合您的一種:
- 您在第一個回圈中立即將每個 TestScore 實體寫入檔案 - 而不是創建一個新的 TestScore 實體!您不需要
TestScore用于輸入所有值的陣列。 - 在創建 的新實體之前,您還可以
array在輸入中創建 的新實體TestSuite。所以每個 TestSuite 都有它自己的陣列實體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/433409.html
