Reputation: 2150
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
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
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