Can I print out the name of the variable?

后端 未结 6 695
独厮守ぢ
独厮守ぢ 2021-01-12 15:26

I have created a no. of constant variables, more than 1000, those constants are unique integer.

public static final FOO  335343
public static final BAR  2342         


        
6条回答
  •  一个人的身影
    2021-01-12 15:53

    As I noted in my comment to the original post, I have a strong suspicion that the best solution for your current problem is to solve it in a completely different way. You seem to want to associate an int with a String, and one way to do this is to use a Map such as a HashMap. For e.g.,

    import java.util.HashMap;
    import java.util.Map;
    
    public class MapDemo {
       public static void main(String[] args) {
          Map myMap = new HashMap();
          myMap.put(335343, "FOO");
          myMap.put(234234, "BAR");
          myMap.put(122424, "BEZ");
    
          int[] tests = {335343, 234234, 122424, 101010};
    
          for (int i : tests) {
             // note that null is returned if the key isn't in the map
             System.out.printf("%d corresponds to %s%n", i, myMap.get(i));
          }
       }
    }
    

    Edit 1:
    Per your recent comments and update to your original question, I take it that you have many numbers and their associated Strings involved in this program and that your need is to find the String associated with the number. If so, then you need to think re-design, that the numbers and their strings should not be hard-coded into your program but rather be part of the program's data, perhaps in a text file with one column being the numbers and the next column (separated by a space perhaps), the associated text. This way you could read in the data and use it easily in a HashMap, or data base, or really any way that you desire. This will give your project much greater flexibility and robustness.

提交回复
热议问题