gpt4 book ai didi

java - 获取for循环内的随机值

转载 作者:行者123 更新时间:2023-12-02 12:07:16 25 4
gpt4 key购买 nike

我在这里所做的是尝试生成一个数字并查看它是否与数组中的数字相同。如果相同,系统将重新生成,直至编号唯一。

Random randomno = new Random();
int r = randomno.nextInt(3);

TextView randomnumber = (TextView) findViewById(R.id.TVRno);

int[] arr = new int[2];
arr[0] = 0;
arr[1] = 2;

for(int i = 0; i < arr.length; i++){
if(r == arr[i]){
z = randomno.nextInt(3);
i = 0;
}
}

randomnumber.setText("" + z);

但最终我无法在for循环中打印变量z。如何打印变量 z?我是否使用了错误的方法来执行此操作?

最佳答案

这里的变量z超出了范围。这就是所谓的 block 变量,只能从循环内访问它。要在外部访问它,需要在该循环外部声明它:

Random randomno = new Random();

int r = randomno.nextInt(3);

TextView randomnumber = (TextView) findViewById(R.id.TVRno);

int[] arr = new int[2];

arr[0] = 0;

arr[1] = 2;

int z = 0;

for(int i = 0; i < arr.length; i++){
if(r == arr[i]){
z = randomno.nextInt(3);
i = 0;
}
}
randomnumber.setText("" + z);

再看一遍,您似乎从未初始化过 z,无论是内部还是外部。你的代码崩溃了吗?如果是这样,那就是原因。

旁注:您可以像这样初始化该数组:int arr = new int[] {0,20};

关于java - 获取for循环内的随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46815834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com