簡體   English   中英

如何在變量末尾附加一個數字來調用本地存儲的變量? java的

[英]How to attach a number at the end of a variable to call on a locally stored variable? java

這有點難以解釋,但在我的程序中,我有一個帶計數器的循環,所以每次循環計數增加一。 循環將從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]);

假設您的變量是字符串(無論如何都可以替換為任何類):

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

如果count = 3,則需要第3個變量,但是數組是0索引的,所以你必須這樣做:變量[count - 1]。 而已。

數組可以使您的任務更容易實現:

    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]);
    }
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)+"------------");

如果我正確理解你的問題,那么使用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而不是定義seaprate varaible你可以使用ArrayList存儲值,然后利用訪問它index

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));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM