因此,作为任务的一部分,我被要求创建一个具有一定范围内的随机值的数组,然后将其从小到大排序(我使用了冒泡排序),然后首先打印数组中的所有元素,然后从小到大列出它们。
我的问题是我不断收到 ArrayIndexOutOfBoundsException 错误,但找不到问题所在。
您可以在我放入 randomArrays 方法的代码中看到,一个 for 循环为我在 main 方法中声明的数组大小创建随机值,然后,在 for 循环下面,我创建了一个if 语句检查一个元素的值是否大于其后面的元素,如果是,则交换元素的位置,直到将它们全部排序为最小到最大,然后终止循环。
非常感谢您的帮助,谢谢:)
public class MyArray {
public static void main(String[] args) {
int[] elements = new int[50];
int min = 0;
int max = 50;
randomArrays(elements, max, min);
}
public static void randomArrays(int[] elements, int max, int min) {
int range = max - min; //defines the range of the integers
int temp;
boolean fixed = false;
while (fixed == false) {
fixed = true;
for (int i = 0; i < elements.length; i++) {
elements[i] = min + (int) (Math.random() * range);
while (i < elements.length) {
if (elements[i] > elements[i + 1]) {
//if 8 > 5
temp = elements[i + 1];
//store 5 in temp
elements[i + 1] = elements[i];
//put the 8 in the 5's place
elements[i] = temp;
fixed = false;
}
i++;
}
}
}
}
//System.out.println(elements[i]);
}
最佳答案
My issue is that I keep getting the ArrayIndexOutOfBoundsException error, but cannot find where this problem lies.
问题出在for循环
的条件上。当 i=49
时,您会收到 ArrayOutOfBounds
异常,然后尝试访问不存在的 i+1
索引。
改变
for (int i = 0; i < elements.length; i++)
至
for (int i = 0; i < elements.length-1; i++)
关于java - 尝试使用冒泡排序对随机整数数组从最大到最小进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48172110/