Is it possible to name a variable using a variable in Java?

前端 未结 4 1823
没有蜡笔的小新
没有蜡笔的小新 2020-12-19 20:47

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

相关标签:
4条回答
  • 2020-12-19 21:14

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

    0 讨论(0)
  • 2020-12-19 21:15

    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],...

    0 讨论(0)
  • 2020-12-19 21: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.

    0 讨论(0)
  • 2020-12-19 21:16

    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
    
    0 讨论(0)
提交回复
热议问题