null
null

Reputation: 2150

Declare a new variable for each iteration in a for loop

How would I declare a new variable through each iteration of a for loop?

For example:

for (int i = 1; i <= 4; i++) {
    int var1 = i; // in the second iteration, I want a variable var2 set to i, etc.
}

After the loop is completed, I want 4 variables, named var1, var2, var3, and var4, each set to 1, 2, 3, and 4, respectively (when I set var1 to i in the above code, I am essentially setting it to 1 since that is the value of i throughout that specific iteration).

Upvotes: 1

Views: 8767

Answers (2)

Adrian Shum
Adrian Shum

Reputation: 40076

use array, list, map or other kind of data structure.

e.g.

int[] arr = new int[4];
for (int i = 1; i <= 4; i++) {    // well, we usually write in 0-based manner...
    arr[i-1] = i;
}
// if you want to get n-th value, just do   arr[n-1]


List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i <= 4; i++) {
    list.add(i);
}
// if you want to get n-th value, just do   list.get(n-1)



Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 1; i <= 4; i++) {
    map.put(i, i);
}
// if you want to get n-th value, just do   map.get(n)

something like that.

Upvotes: 3

Juned Ahsan
Juned Ahsan

Reputation: 68715

Either use four variables or use an array. Here is the array alternative:

int arr[] = new int[5];
for (int i = 1; i <= 4; i++) {
   arr[i] = i;
}

Upvotes: 1

Related Questions