0

Ok, say I have the code:

        Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String str = scan.nextLine();
            String[] ss = str.split(" ");
            int[] zz = new int[ss.length];
            for (int i = 0; i < ss.length; i++)
                zz[i] = Integer.parseInt(ss[i]);
            int[][] arr = {
                zz
            };

And I want to add zz every time into arr without removing the previous value. How would I go by on doing this?

Nick
  • 1,417
  • 1
  • 14
  • 21
user3212622
  • 125
  • 1
  • 1
  • 5
  • 2
    If I understand the problem correctly, what you want to do is initialize arr outside of the loop. Unfortunately, you dont know how how long scan.hasNext() will run for, so arr needs to be dynamically sized. An ArrayList object may be better suited. – EyeOfTheHawks Jul 04 '14 at 20:25
  • 1
    Count how many lines there are beforehand, initialize the array properly, do the actual work. Or, as EyeOfTheHawks said, use an ArrayList. – Steffen Jul 04 '14 at 20:30

3 Answers3

1
    ArrayList<int[]> arrayList = new ArrayList<>();
    Scanner scan = new Scanner(System.in);
    while (scan.hasNext()) {
        String str = scan.nextLine();
        String[] ss = str.split(" ");
        int[] zz = new int[ss.length];
        for (int i = 0; i < ss.length; i++)
            zz[i] = Integer.parseInt(ss[i]);
        arrayList.add(zz);
    }
    int[][] arr = arrayList.toArray(new int[0][0]);
user483178
  • 26
  • 1
0

There is an excellent example of how to implement your own two-dimensional ArrayList and (re-) use it in your specific case:

How to create a Multidimensional ArrayList in Java?

No need to reinvent the wheel, go for it!

Community
  • 1
  • 1
frhd
  • 9,396
  • 5
  • 24
  • 41
0

Create a global-ish variable int[][] arr before the for loop, then Put arr[][] = {} into the for loop:

Scanner scan = new Scanner(System.in);
        while (scan.hasNext()) {
            String str = scan.nextLine();
            String[] ss = str.split(" ");
            int[] zz = new int[ss.length];
            int[][] arr = new int[ss.length][ss.length];
            for (int i = 0; i < ss.length; i++){
                zz[i] = Integer.parseInt(ss[i]);
               arr[i] = {
                    zz
                };

you are putting zz into the arr array of index "i", so the values would be put in once every loop.

Hope this helps, Classic.

EDToaster
  • 3,160
  • 3
  • 16
  • 25