gpt4 book ai didi

Java:数组索引越界异常

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:07:52 25 4
gpt4 key购买 nike

System.out.print("Enter an integer:  ");
Scanner sc = new Scanner(System.in);

int x = sc.nextInt();
int lArray = x - 2;
int[] newArray = new int[lArray];

System.out.println("Let's display all possible integers...");
for (int i = 0; i <= newArray.length; i++) {
newArray[i] = i + 2;
System.out.print(newArray[i] + " ");
}

我最近才开始使用 Java,但我敢肯定,如果我用另一种语言编写类似的代码,我也会遇到同样的问题。这是一个应用程序的摘录,其中列出了用户输入之前的所有素数。

之所以使用 x-2 作为 lArray 的定义,是因为数组的长度将是从 2 到数字 {2, 3, 4, 5... x} 的所有整数。

我注意到这条线

for (int i = 0; i <= newArray.length; i++) {

如果我改变 i <= newArrayi < newArray ,代码可以正常工作。但是,如果 x 是素数,则用户的输入 x 会被遗漏,这是一个问题。

最佳答案

你应该使用 <而不是 <=在:

for (int i = 0; i <= newArray.length; i++)
^^

如果foo任何数组,foo 的有效索引是 [0,foo.length-1]

使用 foo.length作为索引将导致 ArrayIndexOutofBoundsException .

还有lArray其中包含自然数的数量 <=x但仅排除一个 号码 1 , 它的值应该是 x-1而不是 x-2 .

关于Java:数组索引越界异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3951252/

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