2

Hey is there a way to create multiple variables in a for loop? Here is an example of what i "want" my code to look like

for(int i=0; i<10; i++) {
    int[] arr(i) = new int[i+1];
    for(int j=0; j<=i; j++) {
        arr(i)[j] = j+1;
    } //for
} //for

I want to create 10 arrays like this:

arr0: [1]
arr1: [1, 2]
arr2: [1, 2, 3]
arr3: etc
...
3
  • 1
    In Java you cannot make variable names at run-time like this. You can use an int [][] in order to handle 2 dimensional arrays, or just use a List of List. Commented Feb 5, 2020 at 20:40
  • So that means i have to make 10 arrays by hand? Or is there a way of doing that smarter. How do i create for a example 1000arrays of name array1, array2, array3 without doing it by hand Commented Feb 5, 2020 at 20:45
  • No you just need to use loops to do it, if you ever are doing something like array1 array2, by hand with numbers at the end, chances are you don't actually need to do it by hand. Commented Feb 5, 2020 at 20:46

2 Answers 2

4

You can do it using a 2-D array as shown below:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        int[][] arr = new int[10][];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = new int[i + 1];
            for (int j = 0; j < arr[i].length; j++) {
                arr[i][j] = j + 1;
            }
        }

        for (int i = 0; i < arr.length; i++) {
            System.out.println("arr" + i + ": " + Arrays.toString(arr[i]));
        }
    }
}

Output:

arr0: [1]
arr1: [1, 2]
arr2: [1, 2, 3]
arr3: [1, 2, 3, 4]
arr4: [1, 2, 3, 4, 5]
arr5: [1, 2, 3, 4, 5, 6]
arr6: [1, 2, 3, 4, 5, 6, 7]
arr7: [1, 2, 3, 4, 5, 6, 7, 8]
arr8: [1, 2, 3, 4, 5, 6, 7, 8, 9]
arr9: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sign up to request clarification or add additional context in comments.

1 Comment

I have one suggestion, I recommend using i < arr.length instead of i < 10 for your outer loop and when printing, instead of hard coding 10 3 times. This will make it so when you change new int [10] to 100 it will work just fine and won't error out or require you to change the number elsewhere.
3

You cannot create new variables like that. You do have several options.

  1. Used An array of arrays. Sometimes referred to as 2-D arrays.
int[][] v = new int[4][6];

  1. You can also use a map.
Map<String, int[]> arrays = new HashMap<>();

for (int i = 0; i < 10; i++) {
    arrays.put("arr" + i, new int[10]);
}

You can then access each array as a string.

arrays.get("arr1")[4] = 3;

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.