我正在尝试输入一个数字,并让程序创建一个该长度的新数组。然后,我将一次一个地输入数组中的所有元素。之后,我键入一个数字,程序将在数组中搜索该数字。不幸的是,我在下面编写的代码抛出了一个 ArrayIndexOutOfBoundsException
。我该如何解决这个问题?
import java.io.*;
public class aw
{
public static void main(String args [])throws IOException``
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
int z;
boolean vince = false;
System.out.print("Enter Element :");
int a = Integer.parseInt(in.readLine());
int [] jes = new int[a];
for(z=0; z<jes.length; z++)
{
System.out.print("Numbers :");
jes[z] = Integer.parseInt(in.readLine());
}
System.out.print("Enter search:");
int []x = new int [100];
x[100] = Integer.parseInt(in.readLine());
if(jes[z] == x[100])
{
vince = true;
if(vince == true)
{
System.out.print("Array "+jes[z]+ "Found at Index"+z); // here is my problem if i input numbers here it will out of bounds
}
}
}
}
最佳答案
第一个问题是你重用了 z 而没有重置它。您的循环递增 z 直到它大于数组的最大索引 jes
,因此当您尝试重用 z 时,您使用的是超出范围的索引。当您尝试将读入值与 jes
进行比较时,我认为您缺少 for 循环这可能会重置和重用 z,但使用不同的变量来递增可能会更清楚。
第二个是您为 x 声明了一个大小为 100 的数组,并试图访问第 101 个索引(超出范围)。 int[] x = new int[100]
具有 0-99 的指数。
此代码应按预期工作:
import java.io.*;
public class aw
{
public static void main(String args []) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
boolean vince = false;
System.out.print("Enter Element :");
int a = Integer.parseInt(in.readLine());
int [] jes = new int[a];
for(int i=0; i<jes.length; i++) {
System.out.print("Numbers :");
jes[i] = Integer.parseInt(in.readLine());
}
System.out.print("Enter search:");
int x = Integer.parseInt(in.readLine());
for(int i=0; i < jes.length; i++) {
if(jes[i] == x) {
vince = true;
break; //found the value, no need to keep iterating
}
}
if(vince == true) {
System.out.print("Array "+jes[i]+ "Found at Index"+i);
}
}
}
关于java - 如何避免 ArrayIndexOutOfBounds?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337826/