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 called clouds. 2) A ctor that creates the clouds array list with an initial capacity of 100. Look up the javadoc API page for ArrayList to see what ArrayList ctor to call. If you dont know how to do this, ask on Piazza. DONT ask Piazza for the answer, just ask how to find the javadoc API page. 3) A public method called add(Cloud c) that takes a cloud and adds it to the array list. The return type of this method should be boolean, and the method should always return true. Thats a little weird but it will make more sense later. 4) A public float method called getMeanHeight(), which returns the average height of all the clouds in the array list. */

public class Sky {

// a private ArrayList of type Cloud named clouds **** private ArrayList clouds;

// a constructor that creates the clouds array list with // initial capacity of 100 ****

public Sky() { clouds = new ArrayList(100); // clouds.ensureCapacity(100); }

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

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!