gpt4 book ai didi

java - 发现某些内容时不打印 "not found"

转载 作者:行者123 更新时间:2023-12-01 18:16:42 25 4
gpt4 key购买 nike

我正在尝试做这个项目,但由于某种原因,我遇到了一个我一生都无法解决的问题。

public static void printlist(String n){
for(int i=0; i< roomlist.size(); i++){
if(roomlist.get(i).name.equals(n)){
System.out.println("Room Name: " + roomlist.get(i).name + " state: " + roomlist.get(i).state);
System.out.println("Description: " + roomlist.get(i).desc);
System.out.println("Creatures in Room: " + roomlist.get(i).Fred());
if(roomlist.get(i).north != null){
System.out.println("North Neighbor: " + roomlist.get(i).north.name);
}
if (roomlist.get(i).south !=null){
System.out.println("South Neighbor: " + roomlist.get(i).south.name);
}
if (roomlist.get(i).east !=null){
System.out.println("East Neighbor: " + roomlist.get(i).east.name);
}
if (roomlist.get(i).west !=null){
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
}

}
System.out.println("Room " + n + " does not exist!");
}

现在,即使它在 ArrayList 中找到 Room 对象,它仍然会打印“Room "+ n + "does not exit!”我需要它仅在 ArrayList 中找不到房间时才打印该信息

最佳答案

发生这种情况的原因是因为未找到消息是您的方法的最后一条语句。相反,您应该在找到元素并打印所需消息后立即从该方法返回。

例如,假设每个房间都有一个唯一的名称:

...
if (roomlist.get(i).name.equals(n)) {
...
if (roomlist.get(i).west != null) {
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
return;
}
...

关于java - 发现某些内容时不打印 "not found",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29089217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com