import java.util.ArrayList;
public class WeatherData
{
private ArrayList temperatures;
public WeatherData( double[] data )
{
temperatures = new ArrayList();
for( int i = 0; i < data.length; i++ )
{
temperatures.add( data[i] );
}
}
/**
* Cleans the data by removing from temperatures all values that are
* less than lower and all values that are greater than upper,
* as described in part (a)
*/
public void cleanData( double lower, double upper )
{
int i = 0;
/* ------------------------------------------------------
Be carefule with arrayList.delete():
0 1 2 3
Before: | 90.1 | 89.0 | 87.4 | 90.2 |
After delete(1): | 90.1 | 87.4 | 90.2 |
a new element will occupy position 1 !
------------------------------------------------------ */
while(i < temperatures.size())
{
Double t = temperatures.get(i);
// Remove element i is value is outside thresholds
if( t < lower || t > upper )
temperatures.remove(i); // Do NOT advance i
else
i++;
}
}
/**
* Returns the length of the longest heat wave found in temperatures,
* as described in part (b)
* Precondition: There is **at least one** heat wave in temperatures
* based on threshold.
*/
public int longestHeatWave( double threshold )
{
int maxLength = 0; // Take advantage that min >= 1 (given!)
int currentLength = 1; // Each day is a length of 1
for(int i = 1; i < temperatures.size(); i++)
{
Double last = temperatures.get(i - 1);
Double current = temperatures.get(i);
// Check if consecutive days exceed threshold
if( last > threshold && current > threshold )
{
currentLength++; // One more day
// Check if it is longer than maxLength
if(currentLength > maxLength)
maxLength = currentLength;
}
else
{
currentLength = 1; // Back to 1 day length
}
}
return maxLength;
}
public String toString()
{
return temperatures.toString();
}
}
|