Home>

I want to generate a corresponding object for each line of a text file, store it in an Object type array, and output the contents.

Mathematics, 80, Taro Yamada
English, 72, Taro Yamada
Mathematics, 90, Ichiro Suzuki
package test;
import java.io. *;
public class Test {
    public static void main (String [] args) {
        try {
            File file = new File ("test.txt");
            dataRoad (file);
        } catch (IOException e) {
        }
    }
    public static void dataRoad (File file) throws IOException {
        BufferedReader bufferedReader = new BufferedReader (new InputStreamReader (new FileInputStream (file), "UTF-8"));
        Object [] text = new Object [3];
        String textfile;
        String [] splitLine = new String [3];
        int count = 0;
        while ((textfile = bufferedReader.readLine ())! = null) {
            splitLine = textfile.split (",", 0);
            if (splitLine [0] .equals ("math")) {
                text [count] = new Math (splitLine [1], splitLine [2]);
            }
            else if (splitLine [0] .equals ("English")) {
                text [count] = new English (splitLine [1], splitLine [2]);
            }
            count ++;
        }
        bufferedReader.close ();
        System.out.println (text [0] .toString ());
        System.out.println (text [1] .toString ());
        System.out.println (text [2] .toString ());
    }
}
package test;
public class Math {
    private static String score;
    private static String name;
    public Math (String score, String name) {
        this.score = score;
        this.name = name;
    }
    public String toString () {
        return "score =" + this.score + ", name =" + this.name;
    }
}
package test;
public class English {
    private static String score;
    private static String name;
    public English (String score, String name) {
        this.score = score;
        this.name = name;
    }
    public String toString () {
        return "score =" + this.score + ", name =" + this.name;
    }
}

When I execute the above Test.java, I want the output to be as follows.
Score = 80, Name = Taro Yamada
Score = 72, Name = Taro Yamada
Score = 90, Name = Ichiro Suzuki

actually
Score = 90, Name = Ichiro Suzuki
Score = 72, Name = Taro Yamada
Score = 90, Name = Ichiro Suzuki
Will be output.

I thought that the cause was that the element of the String array splitLine was changed in the while statement, but in that case, the second line of the output result is not output as score = 90, name = Ichiro Suzuki. I thought.
Why is the content unified to that of the last created object only for objects of the same class type?

It may be a difficult question to understand, but thanks for your cooperation.