2015-10-05 104 views
2

我收到错误消息后,我进入退出它说数组索引越界的异常:2

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 

林可怕在编程所以请与我裸露

import java.util.*; 

public class Highway{ 

    public static void main(String[] args) { 

     Scanner input = new Scanner(System.in); 

     System.out.println("Total number of the exits"); 
     int p=input.nextInt(); 
     System.out.println("The first exit"); 
     int i=input.nextInt(); 
     System.out.println("The second exit"); 
     int j=input.nextInt(); 

     int[]A= new int[p]; 

     for(int w=0;w<=p;i++) { 


      A[i]=(int)(java.lang.Math.random() * 20 + 1); 
      System.out.println(A[w]); 
     } 
    } 

    static void Distance(int i, int j, int[] A) { 
    // a is the array of distance 
    // this find the distances between i and j 
     int distance = 0; 

     if(j>i){ 
     for(int k = i; k<=j;k++) { 

       distance=distance+A[k]; 
     } 

       distance=distance-A[i]; 

     } 

     if(i>j){ 
      for (int m = j; m<=i; m++){distance=distance+A[m]; 
      } 
       distance=distance-A[j]; 
      } 

      System.out.println("The distance of the first"+i+" and second exit"+j+" is"+distance); 

     } 
} 
+1

这里是堆栈跟踪? –

+0

另外,你有没有尝试单步执行代码来查看哪一行会引发异常? – KornMuffin

回答

4

你的循环重复,直到p包容,这就是你得到错误的地方! 数组的大小是p,您应该迭代的索引是0,...,p-1加上您正在增加i而不是w

修改:

for(int w=0;w<=p;i++) 

到:

for(int w=0;w<p;w++) 
2

更改您的for循环以下

for(int w=0;w<p;w++) { 


     A[w]=(int)(java.lang.Math.random() * 20 + 1); 
     System.out.println(A[w]); 
    } 

唯一的变化我在这里做是在为条件,因为如果大小的数组是p,那么可以在0,1,...,p-1访问数组值。此外,您还需要增加w,而不是i在for循环

此外,该阵列中要更新的A[i]代替A[w]

+0

@alfasin在回答'w'没有得到增加。此外,用户正在更新'A [i]'然后打印'A [w]',这将再次向他显示类似的错误。 –

+0

你是对的 - 赶上! – alfasin

+0

@alfasin希望这个为他人澄清以及:) –