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)
发布于 2021-09-14 04:33:28
你的数组列表有一些空的列表,如果你访问它,它将抛出IndexOutOfBoundsException。
在访问该索引之前,请始终检查该索引中是否存在数据。
https://stackoverflow.com/questions/69171680
复制相似问题