gpt4 book ai didi

java - 为什么我的代码上一直显示 "ArrayIndexOutOfBoundsException"?

转载 作者:行者123 更新时间:2023-12-02 06:24:43 24 4
gpt4 key购买 nike

所以我是编码新手,我正在使用 Drjava。
我刚刚收到类(class)的作业,要求用户将整数输入到两个数组中(用户必须在每个数组中从小到大输入整数)。
然后我必须组合两个数组并将新数组从小到大排序。
我想我知道如何做到这一点并且它会编译得很好,但它一直说在我运行代码并输入一些数字后出现 OutOfBoundsException 。

为什么它总是这样,我该如何解决它?

谢谢。

class Main{

public static void main (String str[]) throws IOException {
Scanner scan = new Scanner (System.in);

System.out.println("Enter the values for the first array, up to 10000 values, enter a negative number to quit");

int[] array1= new int[10000];
int x=0;
int x1=0;
int v=1;
for(int where=1; x>=0; where++) {
x= scan.nextInt();
array1[where]=x;
x1++;
if((array1[where]<array1[where-1])&&(x>=0)){
System.out.println("ERROR: Array not in correct order");
x=-326;}
}

System.out.println("Enter the values for the second array, up to 10000 values, enter a negative number to quit");

int[] array2= new int[10000];
int y=0;
int y1=0;
int w=1;
for(int wher=1; y>=0; wher++) {
y= scan.nextInt();
array2[wher]=y;
y1++;
if((array2[wher]<array2[wher-1])&&(y>=0)){
System.out.println("ERROR: Array not in correct order");
y=-326;}
}

if(x!=-326) {
System.out.println("First Array: ");
int where=x1;
for(v=1; v<(where); v++) {
System.out.println(array1[v]); }}

if(y!=-326) {
System.out.println("Second Array: ");
int wher=y1;
for(w=1; w<(wher); w++) {
System.out.println(array2[w]); }}

int[] array3= new int[v+w];
int a=0;
int b=0;
while((a+b)<(v+w-3)) {
while(array1[v-a]>array2[w-b]) {
array3[w+v-a-b]=array1[v-a];
a++;}
while(array2[w-b]>=array1[v-a]) {
array3[v+w-a-b]=array2[w-b];
b++;}
}

if((y!=-326) && (x!=-326)) {
System.out.println("Merged Array: ");
int c=0;
while((v+w-c)>=2){
System.out.println(array3[v+w-c]);
c++; }
}

}

}

最佳答案

在第一个 for 循环中,当 where = 10000 时,它会尝试访问不存在的 array1[10000]。因此,您正在尝试访问“越界”的索引。

您需要确保不会尝试访问不存在的索引。

由于您定义了 array1 = new int[10000],这意味着您只能访问索引 0 - 9999。任何超过 array1[9999] 的内容都会抛出相同的错误错误“ArrayIndexOutOfBounds”。我认为这是一个非常明确的错误消息。

关于java - 为什么我的代码上一直显示 "ArrayIndexOutOfBoundsException"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20666615/

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