数组错误Java

时间:2014-10-20 21:08:47

标签: java arrays

当我编译java代码时,我遇到了问题:

线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:11

at watercount.trap(watercount.java:41)
at watercount.main(watercount.java:14)

似乎没有正确使用数组,但我无法弄清楚。谢谢你的帮助!

import java.util.Arrays;


public class watercount {

    public static void main (String args[]){

    int[] Array = new int[] {1,3,4,6,8,12,2,3,4,5,10};


    int water_num;

    water_num = trap(Array);

    System.out.println(Arrays.toString(Array));


    }



    public static int trap (int[] A) 

    { int trap=0;
      int high=0;

      if (A==null) return trap;

      int []leftHigh = new int[A.length];
      int []rightHigh = new int[A.length];

      for(int i=0; i<A.length; i++){
          if(A[i]>high) high = A[i];
          leftHigh[i]=high;  
      }

      high=0;

      for(int i=A.length;i>=0;i--){
          if(A[i]>high) high = A[i];
          rightHigh[i]=high;  
      }

      for(int i=0; i<A.length; i++)

      {trap+=Math.min(rightHigh[i],leftHigh[i])-A[i];}

     return trap;



    }

1 个答案:

答案 0 :(得分:2)

向后迭代for的第二个i循环从无效索引开始 - A.length。这是一个“一个接一个”的错误。从最大可能索引A.length - 1开始:

for(int i=A.length - 1; i>=0; i--){