gpt4 book ai didi

java - 似乎无法访问我的数组值,即使它正在工作

转载 作者:行者123 更新时间:2023-11-30 02:45:41 24 4
gpt4 key购买 nike

出于某种原因,我似乎无法在我创建的 for 循环之外访问我的数组值。我已经在本地声明了该数组。但是,当我必须用户输入一个值时,由于某种原因,绑定(bind)值一直给我0。有没有办法从 for 循环内的数组中获取信息,进行“概括”,这样就可以在其他函数中使用它。

import java.util.*;

public class Array {

public static void main(String[] args) throws IndexOutOfBoundsException {

int[] array = new int[100];
try{
for(int i: array){
array[i] = (int)(Math.random()*100);
System.out.println(array[i]);
}
Scanner input = new Scanner(System.in);
System.out.println("Please enter an index for which you would like to see: ");
int index = input.nextInt();
System.out.println(array[index]);

}catch(IndexOutOfBoundsException ex){
System.out.println("Please enter in an index thta is not out of bounds");
}finally{System.out.println("--------------------------");}
}
}

最佳答案

尝试使用这个 for 循环,它应该可以工作:

for(int i=0;i<array.length;i++){
array[i] = (int)(Math.random()*100);
System.out.println(array[i]);
}

您的代码中的问题是:

当你执行for(int i: array)时,你只是指示将数组的内容从 array[0] 复制到 array[99] 到 i,这将全部为零没有设置其他值的时间。增强的 for 循环应该仅用于减少代码迭代

要了解增强型 for 循环的工作原理,请尝试下面给出的循环以加深理解:

int[] array = new int[100];
array[0]=1;array[1]=2;

for(int i: array){
// array[i] = (int)(Math.random()*100);
System.out.println(i);
}

当您运行此代码时,第一个和第二个元素将打印 1 和 2。

希望现在一切都清楚了。

关于java - 似乎无法访问我的数组值,即使它正在工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40273539/

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