For a project in school, I was asked to write a program that loops through the values in an ArrayList named revenues and prints whether or not if the numbers withen revenues increased, decreased, or stayed the same while it went through the ArrayList.
This is what I wrote
System.out.println("Year 1: No comperison");
for (int i = 0; i < revenues.size(); i = i + 1){
if (revenues.get(i) < revenues.get(i+1)){
System.out.println("Year "+ (i) +": increased");
} else if (revenues.get(i) > revenues.get(i+1)){
System.out.println("Year "+ (i) +": decreased");
} else {
System.out.println("Year "+ (i) +": stayed the same");
}
}
But whenever I ran the program, it shows me an error message because of this code.
This is the error
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 5 out of bounds for length 5
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
at java.base/java.util.Objects.checkIndex(Objects.java:359)
at java.base/java.util.ArrayList.get(ArrayList.java:427)