我正在尝试做这个项目,出于某种原因,我遇到的问题是,对于我的生活我无法解决。
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 +“不存在!”我需要它只打印,如果在ArrayList中找不到房间
答案 0 :(得分:3)
它发生的原因是因为Not found
消息是您方法的最后一个语句。您应该在找到元素后立即从方法返回并打印出您想要的消息。
例如,假设每个房间都有一个唯一的名称:
...
if (roomlist.get(i).name.equals(n)) {
...
if (roomlist.get(i).west != null) {
System.out.println("West Neighbor: " + roomlist.get(i).west.name);
}
return;
}
...
答案 1 :(得分:1)
基本上,System.out.println("Room " + n + " does not exist!");
将始终执行,因为没有什么能阻止它
假设可能有多个相邻的房间,可能更容易使用简单的标志来指示是否找到了任何房间
public static void printlist(String n){
boolean foundRoom = false;
for(int i=0; i< roomlist.size(); i++){
if(roomlist.get(i).name.equals(n)){
foundRoom = true;
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);
}
}
}
if (!foundRoom) {
System.out.println("Room " + n + " does not exist!");
}
}
你可以通过使用某种类型的List
来存储相邻的房间并在最后检查size
来优化它,但基本的想法仍然是相同的......