如何解决此代码的 java.lang.ArrayIndexOutOfBoundsException 错误?
How to fix this java.lang.ArrayIndexOutOfBoundsException error for this code?
public class 问题 1 {
public static int findmaxdiff (int[] A)
{
int max_diff = 0;
if(A.length>=2)
{
max_diff = A[1] - A[0];
int i, j;
for (i = 0; i < A.length; i++)
{
for (j = i + 1; j < A.length; j++);
{
if (A[j] - A[i] > max_diff) {
max_diff = A[j] - A[i];
}
}
}
}
return max_diff;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// Test your findmaxdiff() method here
int[] testarray1 = {2, 3, 10, 6, 4, 8, 1};
// maxdiff: 8
int[] testarray2 = {7, 9, 1, 6, 3, 2};
// maxdiff: 5
System.out.println(findmaxdiff(testarray1));
// Add test statements
}
}
控制台:
线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:索引 7 超出长度 7 的范围
在实验室 7.Problem1.findmaxdiff(Problem1.java:23)
在实验室 7.Problem1.main(Problem1.java:46)
您的内部 for 循环末尾有一个分号:
for (j = i + 1; j < A.length; j++);
这被解释为 for 循环主体的单个空语句。就好像你输入了这个:
for (j = i + 1; j < A.length; j++) {
;
}
后面的代码块不是 for 循环的一部分,因此它每次都会运行,即使j >= A.length
也是如此。删除分号应该可以解决问题。
public class 问题 1 {
public static int findmaxdiff (int[] A)
{
int max_diff = 0;
if(A.length>=2)
{
max_diff = A[1] - A[0];
int i, j;
for (i = 0; i < A.length; i++)
{
for (j = i + 1; j < A.length; j++);
{
if (A[j] - A[i] > max_diff) {
max_diff = A[j] - A[i];
}
}
}
}
return max_diff;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
// Test your findmaxdiff() method here
int[] testarray1 = {2, 3, 10, 6, 4, 8, 1};
// maxdiff: 8
int[] testarray2 = {7, 9, 1, 6, 3, 2};
// maxdiff: 5
System.out.println(findmaxdiff(testarray1));
// Add test statements
}
}
控制台: 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException:索引 7 超出长度 7 的范围 在实验室 7.Problem1.findmaxdiff(Problem1.java:23) 在实验室 7.Problem1.main(Problem1.java:46)
您的内部 for 循环末尾有一个分号:
for (j = i + 1; j < A.length; j++);
这被解释为 for 循环主体的单个空语句。就好像你输入了这个:
for (j = i + 1; j < A.length; j++) {
;
}
后面的代码块不是 for 循环的一部分,因此它每次都会运行,即使j >= A.length
也是如此。删除分号应该可以解决问题。