Java 搜索未返回对象
作为我对java研究的一部分,我正在尝试创建一个搜索函数,它接受一个参数Java 搜索未返回对象,java,search,object,Java,Search,Object,作为我对java研究的一部分,我正在尝试创建一个搜索函数,它接受一个参数字符串键,该参数与对象平面的目标相关 在此之前,我创建了一个由20个对象组成的队列,每个对象都有不同的参数,现在我正试图通过目标进行搜索 这就是我到目前为止所做的: public Plane searchDestination(String key) { Plane current = first; while(current.destination != key)
字符串键
,该参数与对象平面
的目标
相关
在此之前,我创建了一个由20个对象组成的队列
,每个对象都有不同的参数,现在我正试图通过目标
进行搜索
这就是我到目前为止所做的:
public Plane searchDestination(String key)
{
Plane current = first;
while(current.destination != key)
{
if(current.next == null)
return null;
else
current = current.next;
}
return current;
}
它返回成功构建,但不返回具有匹配条件的对象,我尝试添加System.out.println(当前)代码>后<代码>返回电流代码>但编译器抛出一个错误。我还有一个.displayPlane()代码>函数,该函数应显示所有平面细节(在其他情况下也适用),但当我添加current.displayPlane()时代码>我的后返回当前值代码>我收到一个错误,说它无法访问
我的搜索是否正确,还是遗漏了什么?替换
while(current.destination != key)
与
对于任何对象(如字符串
)比较,应始终使用等于
。不要使用==
或=代码>因为这仅比较对象的引用。对于基本类型数据(如int
),可以使用==
或=代码>您是否考虑过使用目的地到飞机的地图
Map<String, Plane> destToPlane = new HashMap<String,Plane>();
if (destToPlane.containsKey(key))
return destToPlane.get(key);
else
System.out.println("Key not in there");
Map destToPlane=new HashMap();
if(destToPlane.containsKey(关键))
返回destToPlane.get(键);
其他的
System.out.println(“钥匙不在里面”);
不要使用==和!=比较字符串。使用相等。当你收到一条错误信息时,阅读它,如果你不能理解,就发布它。它包含了对问题的精确解释。在这种情况下,编译器继续编译,因为它知道System.out.println永远无法执行,因为该方法返回的时间正好在.putSystem.out.println(current)之前代码>之前<代码>返回当前
进行测试。
Map<String, Plane> destToPlane = new HashMap<String,Plane>();
if (destToPlane.containsKey(key))
return destToPlane.get(key);
else
System.out.println("Key not in there");