Question: Hey guys! can you please help me fix the index out of bound issue here? Error Exception in thread main java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
Hey guys! can you please help me fix the index out of bound issue here?
Error Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at weather.Sky.getMeanHeight(Sky.java:40)
at weather.Sky.main(Sky.java:61)
Code
package weather; import java.util.ArrayList;
/* This class holds lots of cloud instances of various types, and computes the average cloud height. It needs: 1) A private ArrayList
public class Sky {
// a private ArrayList of type Cloud named clouds **** private ArrayList
// a constructor that creates the clouds array list with // initial capacity of 100 ****
public Sky() { clouds = new ArrayList
public boolean add(Cloud c){ clouds.add(c); return true; }
public float getMeanHeight(){ float meanHeight=0; for(int i=0;i<100;i++) { meanHeight=meanHeight+clouds.get(i).getHeight(); // ERROR Line 40*********************** }
meanHeight=meanHeight/100; return meanHeight; }
public static void main(String[] args) {
StratusCloud strat = new StratusCloud(100, 1000); if (!strat.rain().startsWith("It is raining")) System.out.println("Bad StratusCloud::rain"); CumulusCloud cumu = new CumulusCloud(200, 2000); if (!cumu.rain().startsWith("It is raining")) System.out.println("Bad CumulusCloud::rain"); CirrusCloud cirr = new CirrusCloud(300, 3000); if (!cirr.rain().startsWith("I cannot make"); System.out.println("Bad CirrusCloud::rain"); Sky sky = new Sky(); sky.add(strat); sky.add(cumu); sky.add(cirr); float mean = sky.getMeanHeight(); // ERROR line 61********************* if (mean < 1799 || mean > 1801)
System.out.println("Bad mean height: expected 1800, saw " + mean);
System.out.println("Everything (else) is ok");
} }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
