3

What I would like to do is have a loop that names a certain number of variables each time. So sometimes when I run the program, this loop will create say 3 variables a1, a2 & a3 but other times it could name more, e.g. (if this sort of thing were possible):

for(int i=1; i<=n;i++) {
    int ai = i;
}

So in the case (for i=1) the name of the int would be a1 and contains the int 1. This clearly won't work, but I was wondering if there was a way to achieve this effect -- or should I stop hacking and use a different data structure?

Thanks.

Also, this is just an example. I'm using it to create arrays.

1
  • It has been a few years now. Perhaps you can mark one of the Answers to resolve this Question? Commented Aug 12, 2018 at 15:30

4 Answers 4

16

No, this is not possible. Java has no way to construct symbols. However, you can use it to define variable-size arrays. For example:

int[] a = new int[n];
for(int i = 0; i < n; i++) {
    a[i] = i; 
}

Which seems like what you may want.

Sign up to request clarification or add additional context in comments.

Comments

3

Map

Can you use an implementation of Map such as a HashMap?

import java.util.HashMap;
import java.util.Map;


public class test {

    public static void main(String[] args) {

        //Fill your map structure
        Map<String, Integer> theMap = new HashMap<String, Integer>();
        for(int i = 1; i <= 100; i++) {

            theMap.put("a" + i, i);
        }

        //After this you can access to all your values
        System.out.println("a55 value: " + theMap.get("a55"));
    }
}

Program output:

a55 value: 55

Comments

2

Rather than trying to define variables a1, a2, a3, ... you can simply define a fixed size array:

int[] anArray = new int[10]; 

and refer to a[1], a[2], a[3],...

Comments

1

I would just make an array of arrays where the index is equal to the i value.

2 Comments

why would the poster need an array of arrays?
The objects that the asker would be putting into the array that you provided in your answer would be an array as described in his question. So are answers are basically the same except I didn't give the code.

Your Answer

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