我正在尝试用Java编写一个带有三个数组的程序,并返回删除了最低值的数组。我想我正在创建新阵列错误。虽然它似乎编译正常,但每次运行它时,我都收到以下消息:
线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:5
非常感谢任何帮助!
这是我的代码:
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;
}
}
}
答案 0 :(得分:1)
你可能应该发布整个例外:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at LowestGrade.removeLowest(LowestGrade.java:32)
at LowestGrade.main(LowestGrade.java:7)
这意味着您正在访问少于6个元素的数组的第6个元素。在您的情况下,您的数组只有5个元素,其有效索引为0,1,2,3和4.
修复方法是删除嵌套循环:
int lowest = grades [0];
for (int i = 1; i < grades.length; i++)
{
if(lowest > grades[i])
{
lowest = grades[i];
}
}
return removeElement(grades, lowest);
..
public static int[] removeElement(int[] original, int element)
{
int[] n = new int[original.length - 1];
System.arraycopy(original, 0, n, 0, element );
System.arraycopy(original, element+1, n, element, original.length - element-1);
return n;
}
来自this answer的 removeElement
。
答案 1 :(得分:-1)
以下几行是一般编程错误:
newArray[i] = grades[n];
由于newArray大小减少了1,它可以在i = grades.length
时保持该值。
for (int n = 0; n <= grades.length; n++)
当n = grades.length时,grade [n]抛出ArrayIndexOutOfBoundsException异常。所以,应该是for (int n = 0; n < grades.length; n++)
按照您的方式,您可以按如下方式简化和重写方法:
public static int[] removeLowest( int... grades ) {
if ( grades.length <= 1 ) {
return grades;
}
else {
// find lowest first
int lowest = grades[ 0 ];
for ( int i = 1; i < grades.length; i++ ) {
if ( grades[ i ] < lowest ) {
lowest = grades[ i ];
}
}
// build the new array
int[] newArray = new int[ grades.length - 1 ];
for ( int i = 0, j = 0; i < grades.length; i++ ) {
if ( grades[ i ] == lowest ) {
continue;
}
newArray[ j++ ] = grades[ i ];
}
return newArray;
}
}
答案 2 :(得分:-3)
友好提示:检查第二个for
循环的for
- 循环边界。