我正在创建一个酒店程序,其中有一个填充对象(房间)的数组,每个房间都填充了一个客户名称。我使用交换排序按字母顺序对数组进行排序,但是我不断收到错误,指出 Room 无法转换为字符串。 我对 Java 相当陌生,我正在努力寻找解决方案。这是我下面的排序。我怎样才能克服这个问题?
private static void orderedView(Room hotelRef[]) {
for (int i = 0; i < hotelRef.length; i++) {
for (int j = i + 1; j < 12; j++) {
if (hotelRef[i].compareTo(hotelRef[j]) > 0) {
String temp;
temp = hotelRef[i];
hotelRef[i] = hotelRef[j];
hotelRef[j]= temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i = 0; i < hotelRef.length - 1; i++) {
System.out.println(hotelRef[i] + " ");
}
System.out.print(hotelRef[12 - 1]);
}
最佳答案
这里有一些问题:
if (hotelRef[i].compareTo(hotelRef[j])
如果Room
实现Comparable
(或者您有一个自定义Room.compareTo
),实际上是按客户名称进行比较。如果没有,那么也许您需要:if(hotelRef[i].getCustomerName().compareTo(hotelRef[j].getCustomerName()) > 0)
temp = hotelRef[i];
:temp
是一个字符串变量,您正在尝试为其分配一个Room
。将String temp;
更改为Room temp;
如果您使用的是 Java-8 或更高版本,那么您可以使用 Arrays.sort
对其进行更简单的排序和 Comparator.comparing
:
Arrays.sort(hotelRef, Comparator.comparing(Room::getCustomerName));
// or whatever the customer name's getter method is named
关于java - 尝试按字母顺序对对象数组进行排序,但对象无法转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49161080/