Java:数组索引超出界限异常 [英] Java: Array Index Out of Bounds Exception

查看:153
本文介绍了Java:数组索引超出界限异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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,但我确信如果我的编码类似用另一种语言,我会遇到同样的问题。这是一个应用程序的摘录,它列出了用户输入之前的所有素数。

I've just started Java recently, but I sure that if I coded similarly in another language, I would face the same problem. This is an excerpt from an application where it lists all the prime numbers up until the user's input.

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

The reason why x-2 is used as the definition of lArray is because the length of the array will be all the integers from 2 until the number {2, 3, 4, 5... x}.

我注意到该行

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

如果我将 i< = newArray 更改为 i < newArray ,代码可以正常运行。但是,如果x为素数,则省略用户的输入x,这是一个问题。

if I change i <= newArray to i < newArray, the code works without error. However, the user's input, x, is left out which is a problem if x is prime.

推荐答案

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

You should use < and not <= in:

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

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

If foo any array, valid index of foo are [0,foo.length-1]

使用 foo.length as索引将导致 ArrayIndexOutofBoundsException

Using foo.length as an index will cause ArrayIndexOutofBoundsException.

还有 lArray 其中包含自然数< = x 但仅排除 一个 数字 1 ,其值应为 x-1 而不是 x-2

And also lArray which contains number of natural numbers <=x but excluding only one number 1, its value should be x-1 and not x-2.

这篇关于Java:数组索引超出界限异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆