1

I have problem. I try to do develop Program ask me for some numbers a few times. I give list of numbers. I try to save them in List>. Numbers can be split by space. Now I have this code :

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TimeSeries {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Numbers of rows:");
    Scanner in = new Scanner(System.in);
    int NumberLines = in.nextInt();
    in.nextLine();
    String Ciag;
    List<List<Integer>> ll = new ArrayList<List<Integer>>();
    List<Integer> list = new ArrayList<Integer>();
    for (int i = 0; i < NumberLines; i++) {
        list.clear();
        System.out.println("Add row " +(i+1));
        Ciag = in.nextLine();
        for (int t=0; t<Ciag.length(); t++) {

            if(Character.isWhitespace(Ciag.charAt(t)))
            {

            }
            else
            {list.add(Character.getNumericValue(Ciag.charAt(t)));
            }

        }

        System.out.println(list);
        ll.add(list);
        }

    System.out.println(ll);

}


    }

But my output is (example) :

Numbers of rows:
3
Add row 1
0 0 0
[0, 0, 0]
Add row  2
1 2 3
[1, 2, 3]
Add row  3
54 6 8
[5, 4, 6, 8]
[[5, 4, 6, 8], [5, 4, 6, 8], [5, 4, 6, 8]]

But I need to have [[0,0, 0], [1, 2, 3], [5, 4, 6, 8]]

1
  • You are reusing the list reference, so you have added the same List multiple times. Don't reuse the reference. Commented Nov 5, 2016 at 23:12

1 Answer 1

1

The problem is that you add the same list into ll multiple times. You need to add different lists to get the behavior you want. For that, you need to create a fresh new list in each iteration of the for loop, instead of clearing and reusing the existing list.

Change these lines:

List<List<Integer>> ll = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < NumberLines; i++) {
    list.clear();

To this:

List<List<Integer>> ll = new ArrayList<>();
for (int i = 0; i < NumberLines; i++) {
    List<Integer> list = new ArrayList<>();
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.