错误发生在odd[count1] = value
处。
这个程序基本上应该打印一个二维数组
,其中偶数小于奇数,然后从低到高排序。
public static void main(String args[]) {
int[][] arzarehard = {{12,13,17}, {38,44,13}, {54,37,15}, {35,25,17}};
oddSort(arzarehard);
}
public static void oddSort(int[][] thots) {
int [] even = new int[thots.length + thots[0].length];
int [] odd = new int[thots.length + thots[0].length];
for (int i=0; i<even.length; i++) {
even[i] = Integer.MAX_VALUE;
}
for(int i=0; i<odd.length; i++) {
odd[i] = Integer.MAX_VALUE;
}
int count = 0;
int count1 = 0;
//try non for each - possibly causing problem
for (int[] row : thots) {
for(int value : row) {
if (value%2==0) {
even[count] = value;
count++;
} else {
//odd.add(value); - adds it to the end and then concatinate
odd[count1] = value;
count1++;
}
}
}
//even bubble sort
for(int j=0; j<odd.length; j++) {
for(int i=0; i<odd.length-1; i++) {
if(odd[i]>odd[i+1]) {
int temp = odd[i];
int tempTwo = odd[i+1];
odd[i] = tempTwo;
odd[i+1] = temp;
}
}
}
//odd bubble sort
for(int j=0; j<even.length; j++) {
for(int i=0; i<even.length-1; i++) {
if(even[i]>even[i+1]) {
int temp = even[i];
int tempTwo = even[i+1];
even[i] = tempTwo;
even[i+1] = temp;
}
}
}
int e = 0;
int o = 0;
for(int j=0; j<thots.length; j++) {
for(int i=0; i<thots[0].length; i++) {
if(e<even.length) {
thots[j][i] = even[e];
e++;
} else {
thots[j][i] = odd[o];
o++;
}
}
}
for(int[] whatever : thots) {
for( int value : whatever) {
System.out.print(value + " ");
}
System.out.println();
}
}
基本思想是我输入一个二维数组
。然后将该数组分解为偶数和奇数数组。然后将两者分类并重新组合在一起进行打印。
最佳答案
因为在您的代码中,数组 even[]
和 odd[]
的大小为 7
。它应该足以容纳所有值。当您将值 17
分配给 odd[7]
时,这将通过 ArrayIndexOutOfBoundException
实现。
更改代码-
int [] even = new int[thots.length + thots[0].length];
int [] odd = new int[thots.length + thots[0].length];
至-
int [] even = new int[thots.length * thots[0].length];
int [] odd = new int[thots.length * thots[0].length];
关于java - java数组排序偶数和奇数时出现越界异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30344317/