Reputation: 451
I'm wondering how I do the following. Make 10 int variables called, var_0
, var_1
, var_2
, etc.
All holding 0. I'm picturing something like this...
for(int i=0;i>10;i++){
int var_i = 0;
}
But of course it doesn't work. How do I make this work without doing every single variable manually?
It's intended for an arbitrary amount of variables.
Upvotes: 0
Views: 107
Reputation: 4315
It's impossible in Java, there are no macros that would let you do it. Usually if you need 10 variables with same name you just use array.
int vars[] = new vars[10];
It will be initialized to zeroes by default.
If you don't know number of elements in advance you can declare array and construct it later:
int vars[];
...
int numVars = 10;
vars = new int[numVars];
Upvotes: 3
Reputation: 59607
It's intended for an arbitrary amount of variables.
It sounds like you really want an array of 10 int
:
int vars[] = new int[10];
The elements will be initialized to 0. If you need to initialize to something specific, besides zero:
for (int i = 0; i < vars.length; i++)
{
int vars[i] = 7;
}
You could also declare 10 int
, and initialize them in a single statement:
int var1, var2, var3, ...;
var1 = var2 = var3 = ... = 0;
Upvotes: 1
Reputation: 33534
Thats not possible, so better go with arrays
.....
int[] arr = new int[10];
for(int i=0 ; i<10 ; i++){
int[0] = 0;
}
Upvotes: 1
Reputation: 240860
That is not possible, even if it creates it would be local to loop, so why not populate a List
there
List<Integer> numbers = new ArrayList<Integer>();
for(int i=0;i>10;i++){
numbers.add(0);
}
Upvotes: 1