2013-12-18 46 views
0

所以我是新来的编码,我使用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++;     } 
      } 

    } 

} 
+0

你应该使用更简单的变量。我看到有人第一次使用'where'作为整数变量for循环:-P –

+0

如果使用相关语言标记(即[tag:java]),则代码块将突出显示您的语法。 – thegrinner

+0

你可能想到的一件事是命名变量是合乎逻辑的。最后我检查 - 单个字母不是一个伟大的变量名,除非你写一个代数例程... –

回答

2

在你的第一个for循环,当where = 10000,它试图访问array1[10000],它不存在。所以你试图访问一个“超出界限”的索引。

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

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

+0

@Matthew吴FYI ....数组是零索引。这意味着您的10000个元素的数组实际上使用0到9999的索引 – rrirower

+0

@Mthethew Wu请接受解决您问题的答案。上面的答案似乎是正确的,至少你可以做的是用解决你的问题的公认答案奖励他。 – Rawa

相关问题