所以我是新来的编码,我使用Drjava。
我刚刚从我的课得到一个任务,要求用户将整数输入到两个数组(用户必须在每个数组中输入从最小到最大的整数)。
然后,我必须将两个数组组合起来,并将新数组从最小到最大。
我想我想出了如何做到这一点,它会编译得很好,但它一直说在我运行代码并输入了一些数字后出现了OutOfBoundsException。为什么它会在我的代码中说“ArrayIndexOutOfBoundsException”?
为什么它会一直这样做,我该如何解决它?
谢谢。
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++; }
}
}
}
你应该使用更简单的变量。我看到有人第一次使用'where'作为整数变量for循环:-P –
如果使用相关语言标记(即[tag:java]),则代码块将突出显示您的语法。 – thegrinner
你可能想到的一件事是命名变量是合乎逻辑的。最后我检查 - 单个字母不是一个伟大的变量名,除非你写一个代数例程... –