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]?

1
  • what about array or List? Commented Apr 12, 2013 at 14:15

1 Answer 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));
}
Sign up to request clarification or add additional context in comments.

1 Comment

My tip would lean towards using the list variant, I only use arrays when I absolutely must due to an old API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.