0

I am making lots of variables but I want to do this through a while statement.

The problem is that I cannot figure out how to use a variable as part of a variable name so that the variable being created in the loop id not created multiple times (and hence causing an error).

I have a loop like this:

int index = 0
while (index < 10){
    JLabel A1 = new JLabel("A" + [index]);
    index++;
}

Obviously I do not want all my variables called A1 as this isn't legal syntax. How do I have it so that my variables will be A[index]?

4

1 回答 1

11

You don't, basically. Variable names are defined at compile-time.

You either want some sort of index-based collection (array, list) or a string-keyed collection (e.g. a HashMap<String, JLabel>).

If you only want to access by index and you don't need to add items later, then just use an array:

JLabel[] labels = new JLabel[10];
for (int i = 0; i < labels.length; i++) {
    labels[i] = new JLabel("A" + i);
}

Or for a list:

List<JLabel> labels = new ArrayList<JLabel>();
for (int i = 0; i < 10; i++) {
    labels.add(new JLabel("A" + i));
}
于 2013-04-12T14:12:16.080 回答