序列化麻烦

时间:2019-05-26 08:42:01

标签: java serialization deserialization

我创建了一个TestScores类,并对其进行了修改以处理某些异常。我应该序列化类中的内容。我的教科书无法很好地解释这一点,因此我需要帮助。我的TestScores类工作正常,我只是不了解序列化部分。

我使用了本书中的示例,并试图对其进行建模

public class TestScores implements Serializable
{
    //Integer array will hold test scores
    private int[] scores;

public TestScores(int[] newScores) throws InvalidTestScore
{
    scores = newScores;
}

// Method will calculate average of test scores
public  int getAverageScore() throws InvalidTestScore
{
    // Will hold score total
    int total = 0;
    // will hold average of score
    int average = 0;

    //Loop will scan index of the scores array in order to attain the scores
    // A try statement is used to catch any score that is outside of the range(0-100)
    for(int index = 0; index < scores.length; index++)
    {
        total += scores[index]; 

        average = total/scores.length;

        try
        {
            if(scores[index] < 0 || scores[index] > 100)
            {
                throw new InvalidTestScore("Index is " + index + " Score is " + scores[index]);
            }
        }
        catch(InvalidTestScore e)
        {
            System.out.println("Error: Scores can only range between 0 and 100 " + "\n" + e.getMessage());
        }

    }  
    return average;
}


// getAverage method is demonstrated in a main menthod

public static void main(String[] args) throws InvalidTestScore,FileNotFoundException,IOException
{
    //int[] newScores = new int[10];
    int[] scores ={92,64,76,88,53,80,96,60,70,103};
    TestScores test = new TestScores(scores);

    System.out.println(test.getAverageScore());
}

}

public class Serialize implements Serializable
{
    public static void main(String[] args) throws IOException
    {
        TestScores test = new TestScores();
        FileOutputStream outStream = new FileOutputStream("Scores.dat"); 
        ObjectOutputStream objectOutputFile = new ObjectOutputStream(outStream); 
        objectOutputFile.writeObject(test); 
    }
}

0 个答案:

没有答案