[英]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.