Java.lang.arrayindexoutofboundsexception:java编译中的3个错误 [英] Java.lang.arrayindexoutofboundsexception:3 error in java compilation
问题描述
您好,我正在尝试使用冒泡排序对2d数组程序进行排序但是当我编译程序时,它运行到程序的特定部分,它打印出2d数组,但是,当它到达排序部分时,我收到一个错误,java.lang.Arrayindexoutofboundsexception:3。请告诉我如何摆脱这个错误。请参阅下面的代码。
我尝试过:
Hello, I am trying to sort 2d array program using bubble sort but when I compile the program, it runs to the specific part of the program, It prints out the 2d array, But, when it reaches to the sorting part, I get an error, "java.lang.Arrayindexoutofboundsexception:3". Please tell me how to get rid of this error. See the code below.
What I have tried:
import java.util.Random;
import java.util.Scanner;
public class arrays {
public static void main(String[] args) {
Random ran= new Random();
Scanner scan = new Scanner(System.in);
int num,secnum,temp,i,j,k;
System.out.println("Please enter a num.");
num= scan.nextInt();
System.out.println("Please enter another value.");
secnum = scan.nextInt();
int arrayi[][] = new int[num][secnum];
for( i =0; i< num ; i++) {
for( j =0; j< secnum; j++) {
arrayi[i][j]= ran.nextInt(100);
}
}
System.out.println("The array is below:");
for(i =0; i< num ; i++) {
for( j =0; j< secnum; j++) {
System.out.print(arrayi[i][j] + " ");
}
System.out.println();
}
for( i =0; i< num ; i++) {
for( j =0; j< secnum; j++) {
for( k=0; k <secnum; k++) {
if(arrayi[i][k] > arrayi[i][k+1] ) {
temp = arrayi[i][k];
arrayi[i][k] = arrayi[i][k+1];
arrayi[i][k+1] = temp;
}
}
}
}
System.out.println("Sorted array is below:");
for( i =0; i< num ; i++) {
for( j =0; j< secnum; j++) {
System.out.print(arrayi[i][j] + " ");
}
System.out.println();
}
scan.close();
}
}
推荐答案
for( k=0; k < secnum; k++) {
if(arrayi[i][k] > arrayi[i][k+1] )
array [i]
的长度是 secnum
。因此,您可以访问的最大索引是 secnum - 1
。
当循环到达最后一次迭代时, k = secnum - 1
,因此您无法访问 arrayi [i] [k + 1]
,因为这是在外面数组的界限。
(你可以通过使用调试器轻松找到它。)
将你的循环改为:
The length of array[i]
is secnum
. Therefore, the maximum index you can access is secnum - 1
.
When your loop reaches the final iteration, k = secnum - 1
, so you cannot access arrayi[i][k + 1]
, because that is outside the bounds of the array.
(You could have easily found this out for yourself by using the debugger.)
Change your loop to:
for ( k=0; k < secnum - 1; k++) {
这篇关于Java.lang.arrayindexoutofboundsexception:java编译中的3个错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!