我有一个从用户读取到数组列表中的对象数组,当我尝试根据字符串参数对这些数据进行冒泡排序时,程序会遇到运行时错误,并且代码不会执行。
Resort temp;
while (finished = true) {
finished = false;
for (int index = 0; index < numResorts - 1; index++) {
String nam1 = resorts.get(index).getName();
String nam2 = resorts.get(index + 1).getName();
if (nam1.compareTo(nam2) > 0) {
temp = resorts.get(index);
resorts.set(index, resorts.get(index + 1));
resorts.set(index + 1, temp);
//resorts.get(index) = resorts.get(index + 1);
//resorts.get(index + 1) = temp;
finished = true;
}
}
}
最佳答案
您注意到那里有一个无限循环吗?以下 while
循环:
while (finished = true)
...始终无限执行,因为由于该赋值,表达式的计算结果始终为 true
。这就是为什么您不应该比较 boolean 值的原因。只需执行以下操作:
while (finished) // this is enough.
关于java - 冒泡排序数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18968446/