有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在变量末尾附加一个数字来调用本地存储的变量?JAVA

这有点难以解释,但在我的程序中,我有一个带计数器的循环,因此每次循环进行时,计数都会增加1。循环将运行1到10次的随机次数,我在本地存储了名为variable1、variable2、variable3等的变量。假设循环运行三次,因此计数为=3。是否仍有基于计数值检索variable3的方法?就像某些代码等于变量[count]

例如:

String Variable1 = yes

String Variable2 = no

String Variable3 = maybe

String Variable4 = possibly

int count = 1;
while (randomnumber < 10 ){
count = count + 1;
System.out.print(Variable[count]);

共 (4) 个答案

  1. # 1 楼答案

    假设变量是字符串(无论如何都可以用任何类替换):

    String[] variables = { "str1", "str2", "str3" };
    

    如果count=3,则需要第三个变量,但数组是0索引的,因此必须这样做:variables[count-1]。就这样

  2. # 2 楼答案

    List variables= new ArrayList();
    variables.add("k1");
    variables.add("k2");
    variables.add("k3");
    System.out.println("----------------"+variables.get(0)+"------------");
    System.out.println("----------------"+variables.get(1)+"------------");
    System.out.println("----------------"+variables.get(2)+"------------");
    
  3. # 3 楼答案

    如果我正确理解了你的问题,那么不要为不同的值定义不同的变量,而是使用ArrayList

    ArrayList<String> list = new ArrayList<String>();
    for(int i=0;i<10;i++)
    {
        list.add("Value at index:"+i);
    }
    

    要访问上一个索引的值,可以使用:

    System.out.println(list.get(list.size()-1));
    

    这将为您提供列表中的最后一个值:

    Value at index:9
    

    Update1您可以使用ArrayList存储值,然后使用index访问它,而不是定义seaprate变量

    ArrayList<String> list = new ArrayList<String>();
    list.add("yes");
    list.add("no");
    list.add("maybe");
    list.add("possibly");
    
    int count=0;
    int randomNumber=7;
    while (randomNumber < 10 && count<list.size()){
        count = count + 1;
        System.out.println(list.get(count-1));
    }
    
  4. # 4 楼答案

    阵列可以使您的任务更容易实现这一点:

        String[] option={"yes", "no", "maybe", "possibly"};
    
        int count = 1;
        while (randomnumber < 10 && count <= option.length){ //if count is more than array option's size, arrayIndexOutOfBoundException
            count = count + 1;
            System.out.print(option[count-1]);
        }