0

I want to save data in a list that's the instance of another list. like a 2D ArrayList But, data is not being read properly

here is the code of constructor

ArrayList<ArrayList<Integer>> Planets;
Planets = new ArrayList<ArrayList<Integer>>();

here is the function that is reading data from file

public boolean readFile(String str){
    try(BufferedReader br = new BufferedReader(new FileReader(str))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        ArrayList temp = new ArrayList<Integer>();
        while (line != null) {
            temp.addAll(Arrays.asList(line.split(" ")));
            temp = getIntegerArray(temp);

            Planets.add(temp);
            temp.clear();

            line = br.readLine();
        }
        System.out.println(Planets);
    }
    catch(Exception e){
        return false;
    }
    return true;
}

Here is the content of file "input.txt"

1 0 0 0 0 0 0 0 1 0
1 1 1 1 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0

Generated output for System.out.println(Planets); is

[[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], []]

But it should be

[[1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

I dont know where is the problem. Anyone who know, Please help me.

1 Answer 1

3

Try this..

Do that initilize ArrayList temp = new ArrayList<Integer>(); inside while loop and remove temp.clear(); like below

    StringBuilder sb = new StringBuilder();
    String line = br.readLine();
    while (line != null) {
        ArrayList temp = new ArrayList<Integer>();
        temp.addAll(Arrays.asList(line.split(" ")));
        temp = getIntegerArray(temp);

        Planets.add(temp);

        line = br.readLine();
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.