我正在编写一个方法来查找 ArrayList 中的对象。如果我能找到该对象,我会将其打印到屏幕上,否则我将打印一条错误消息,指出“未找到对象”。我遇到的问题是,由于我的方法是对象“十二面体”,而不是 boolean 值,所以我无法使用 if 语句来比较该对象是否存在于数组中。我还能如何解决这个问题?
这是我的主要方法中的代码。
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)) {
最佳答案
检查返回值是否为null。
if (myDList.findDodecahedron(label) != null)
您需要更新 findDodecahedron()
以在未找到任何内容时返回 null,而不是新对象。更改 result
的初始值将实现以下目的:
Dodecahedron result = null;
或者,如果您在找到形状后立即返回形状,则可以摆脱 index
和 result
。无需保存其索引,然后在循环结束后查找索引。
public Dodecahedron findDodecahedron(String label1In) {
for (Dodecahedron d : dList) {
if (d.getLabel().equalsIgnoreCase(label1In)) {
return d;
}
}
return null;
}
您还可以使用 Java 8 流进一步简化它:
public Dodecahedron findDodecahedron(String label1In) {
return dList.stream()
.filter(d -> d.getLabel().equalsIgnoreCase(label1In))
.findAny()
.orElse(null);
}
关于java - 尝试比较对象无法使用IF语句JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52542843/