【发布时间】:2023-03-03 11:52:01
【问题描述】:
我正在编写一种在 ArrayList 中查找对象的方法。如果我能找到对象,我会将其打印到屏幕上,否则我将打印一条错误消息,指出“找不到对象”。我遇到的问题是因为我的方法是对象“十二面体”,而不是布尔值,所以我不能使用 if 语句来比较对象是否存在于数组中。我还能如何处理这个问题?
这是我的 main 方法中的代码。
System.out.print("\tLabel: ");
label = userInput.nextLine();
if(myDList.findDodecahedron(label)) {
System.out.print(myDList.findDodecahedron(label));
}
else {
System.out.print("\t\"" + label + "\" not found");
}
System.out.print("\n\nEnter Code [R, P, S, A, D, F, E, or Q]: ");
break;
这是我的方法。
public Dodecahedron findDodecahedron(String label1In) {
String label = "";
String color = "";
double edge = 0;
Dodecahedron result = new Dodecahedron(label, color, edge);
int index = -1;
for (Dodecahedron d : dList) {
if (d.getLabel().equalsIgnoreCase(label1In)) {
index = dList.indexOf(d);
break;
}
}
if (index >= 0) {
dList.get(index);
result = dList.get(index);
}
return result;
}
这是我尝试编译时遇到的错误。
DodecahedronListAppMenu.java:99: error: incompatible types: Dodecahedron cannot be converted to boolean
if(myDList.findDodecahedron(label)) {
【问题讨论】:
标签: java object if-statement arraylist boolean