-3
當我編譯Java代碼,我遇到的問題:陣列錯誤的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;
}
有數百,甚至數千的會爲你提供了一個解決方案堆棧溢出之前回答問題。請通過搜索Stack Overflow和Google *之前的*來提出問題 - 尤其是關於這個問題一樣常見的問題。 – MarsAtomic 2014-10-20 21:13:20