为什么我的对象数组没有正确生成?

发布于 2025-01-10 09:18:43 字数 2850 浏览 0 评论 0原文

我试图为我的 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]);
    }

Im trying to make an object array for my TestScores class which takes in an array and then can use the averageScore method to get the average score. However it seems like it only writes the last value of the object array as the output simply prints the last value that was inputted. I've tried using a system print line to get the object array output while in the for loop that populates it, which seems to work fine, but outside the loop it doesn't seem to give the expected output, which would be the average of each array inputted into the class.

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());
    }
}

}

As per the comments, I changed my code and instead made it an array of arrays, so I wasn't using the same array for the entire program.

    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]);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白色秋天 2025-01-17 09:18:43

您将输入数据的相同数组添加到所有TestScore对象。因此,如果您修改 TestScore 实例的后续实例的 array,您也会修改所有先前创建的实例。

有两种可能对我有用的解决方案,请选择更适合您的解决方案:

  1. 您在第一个循环中立即将每个 TestScore 实例写入文件 - 而不是创建一个新的 TestScore 实例!您不需要使用 TestScore 数组来输入所有值。
  2. 在创建 TestSuite 的新实例之前,您还可以在输入中创建一个新的 array 实例。所以每个 TestSuite 都有它自己的数组实例。

You add the same array of input data to all the TestScore objects. So if you modify array for subsequent instances of TestScore instances, you also modify all previously created instances.

There are two possible solutions that appear useful to me, pick the one that suits better for you:

  1. You write each TestScore instance immediately to the file within the first loop - instead of creating a new instance of TestScore! You don't need to have an array of TestScore for inputting all the values.
  2. You also create a new instance of array in the input before you create a new instance of TestSuite. So each TestSuite has it's own instance of array.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文