I cannot find a logistic algorithm to find the maximum difference between two consecutive indexes in an array. When I used the method in my code, my client page gave me an error saying I have an outofbounds Exception. Any suggestions? If you need more code then just ask.
//method returning the largest change between two consecutive days
public int NetChange()
{
int BiggestNet = temps[0] - temps[1];
for( int i = 0; i < temps.length; i++ )
{
if( (temps[i] - temps[i+1]) > BiggestNet )
{
BiggestNet = (temps[i] - temps[i+1]);
}
}
return BiggestNet;
}
Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
at Forecast.NetChange(Forecast.java:105)
at Forecast.toString(Forecast.java:120)
at ForecastClient.main(ForecastClient.java:12
Change
for( int i = 0; i < temps.length; i++ )
To
for( int i = 0; i < temps.length - 1; i++ )
temps.length
will give you the length of the array not using zero based counting, but it is accessed by zero based indicies. So if i = temps.length - 1, that is actually the last element in the array. If you then try to access temps[i+1] that will be longer than your array and thus out of bounds.