I'm trying to write a program in Java that takes three arrays and returns the arrays with the lowest value removed. I think I'm creating the new array wrong. While it seems to compile fine, every time I run it, I get the following message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
Any help would be greatly appreciated!
Here is my code:
import java.util.Arrays;
class LowestGrade
{
public static void main (String [] args)
{
int [] a = removeLowest (23, 90, 47, 55, 88);
int [] b = removeLowest (85, 93, 42);
int [] c = removeLowest (59, 92, 93, 47, 88, 47);
System.out.println ("a = " + Arrays.toString(a));
System.out.println ("b = " + Arrays.toString(b));
System.out.println ("c = " + Arrays.toString(c));
}
public static int[] removeLowest (int...grades)
{
if (grades.length <= 1)
{
return grades;
}
else
{
int [] newArray = new int [grades.length - 1];
int lowest = grades [0];
for (int i = 0; i < grades.length; i++)
{
for (int n = 0; n <= grades.length; n++)
{
if (grades[n] > lowest)
{
newArray[i] = grades[n];
i++;
}
else
{
lowest = grades[n];
}
}
}
return newArray;
}
}
}