如何在变量末尾附加一个数字来调用本地存储的变量?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]);
# 1 楼答案
假设变量是字符串(无论如何都可以用任何类替换):
如果count=3,则需要第三个变量,但数组是0索引的,因此必须这样做:variables[count-1]。就这样
# 2 楼答案
# 3 楼答案
如果我正确理解了你的问题,那么不要为不同的值定义不同的变量,而是使用
ArrayList
要访问上一个索引的值,可以使用:
这将为您提供列表中的最后一个值:
Update1您可以使用
ArrayList
存储值,然后使用index
访问它,而不是定义seaprate变量# 4 楼答案
阵列可以使您的任务更容易实现这一点: