我有一个从用户读入arraylist的对象数组,当我尝试根据String参数对这些数据进行冒泡排序时,程序会遇到运行时错误并且代码不会执行。
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;
}
}
}
答案 0 :(得分:3)
你注意到那里有一个无限循环?以下while
循环:
while (finished = true)
...总是无限执行,因为表达式始终评估为true
,因为该赋值。这就是为什么你不应该比较布尔值的原因。只需:
while (finished) // this is enough.
答案 1 :(得分:0)
这是我的解决方案:
List<Integer> sortedlists = new ArrayList<Integer>();
public List<Integer> sortBs(List<Integer> al) {
sortedlists = al;
for(Integer out = al.size()-1; out>1; out--) {
for(Integer i = 0; i < out;i ++){
int n = i+1;
if(sortedlists.get(i) > sortedlists.get(n)) {
Integer temp = sortedlists.get(i);
sortedlists.set(i, sortedlists.get(n));
sortedlists.set(n, temp);
}
}
}
return sortedlists;
}