0

Currently working on a Java project, however I've encountered a bit of a problem involving having a variable number increment in Java, simply due to my lack of knowledge; I'm a beginner.

I'm used to using Batch files, where for this I'd do something along the lines of;

for /l %%a in (1,1,100) do {
set variable%%a = (The value)
}

Where each time it goes through the loop, it would set a new variable; variable1, variable2, variable3 etc. However, hence being here, I have no idea what I'd do to put a value into a variable name in Java, in which the variable would increment each time the loop was passed as declared by for (int i = 0; i < 10; i++). What would I have to do to declare that value in the name of a variable, such as variable(i) = 5 continuously?

2 Answers2

3

You can use a Map (variable name as key, value as value):

final Map<String, Integer> map = new HashMap<String, Integer>();
for (int i; i < 10; i++) {
    map.put("variable" + i, i);
}
// use the map, for example: map.get("variable5") // = 5
0

No you cannot do that. You have to make use of array or collections to set a collection of values.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136