[英]Arraylist java.lang.IndexOutOfBoundsException: Index 3 out of bounds for length 3 Error
[英]java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
import java.util.*;
class stockbuysell{
//Function to find the days of buying and selling stock for max profit.
public static void main(String []args){
int A[] = {100,180,260,310,40,535,695};
ArrayList<ArrayList<Integer>> al = stockBuySell(A,7);
}
static ArrayList<ArrayList<Integer> > stockBuySell(int A[], int n) {
// code here
// buy = 0;
//sell = 1
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();
int flag = 0;
int idx = 0;
for(int i=1;i<n;i++){
if(i==n-1 && flag==1){
al.get(idx).add(i);
flag = 0;
}
if(flag == 0 && A[i]>A[i-1]){//
al.add(new ArrayList<Integer>());
al.get(idx).add(i-1);
flag = 1;
}
if(flag == 1 && A[i]<A[i-1]){//
al.get(idx).add(i-1);
flag = 0;
idx++;
}
}
for(int i=0;i<al.size();i++){
System.out.println(al.get(i).get(0)+" "+al.get(i).get(1));
}
return al;
}
}
我不知道我哪里出錯了。 編譯成功,運行時顯示:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at stockbuysell.stockBuySell(stockBuySell.java:32)
at stockbuysell.main(stockBuySell.java:6)
如果你運行這段代碼
System.out.println(arrayListName.get(arrayListName.size()-1));
編譯成功,運行時顯示:Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
當數組列表為空並且您以這種方式從中搜索值時,您會收到錯誤。 但是如果你檢查你的數組列表是否為空。 當數組列表中至少有一個元素時,運行代碼並獲得值——沒有編譯器錯誤。
public static void functionNameHere(){
if (!arrayListName.isEmpty() ){
//execute code
System.out.println(arrayListName.get(arrayListName.size()-1));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.