循环失败时打印消息
Print message when loop fails
我想了解为什么我无法打印出我想要的结果。我已经更改了几次循环逻辑,但看不到问题。
我有一个数组列表ArrayList<Landing> landings = new ArrayList<>();
我在Landing
class中有以下方法查看登陆ID;
public boolean checkId(int id) {
if (this.landingId == id) {
return true;
} else {
return false;
}
}
我正在尝试创建一些输入处理,如果用户输入的 ID 与数组列表中的 ID 不匹配,则会打印一条错误消息。我似乎无法获得打印消息的失败场景
System.out.print("Please enter the landing ID: ");
int id = Integer.parseInt(sc.nextLine());
boolean unsuccessful = false;
for (int i = 0; i < landings.size(); i++) {
if (landings.get(i).checkId(id)) {
landings.get(i).printLandings();
unsuccessful = false;
break;
} else {
unsuccessful = true;
}
}
if (unsuccessful) {
System.out.println(
"\nThe ID you enterred does not match any landing");
}
break;
TIA
如果你想检查是否有“任何”(=至少一个)匹配,你必须从 boolean unsuccessful = true
.
开始
我们来看最简单的情况:当List
为空时,循环不会运行一次。虽然 unsuccessful
不会改变并且必须在循环之前设置为 true
。
这是一个简化版本。
boolean unsuccessful = true
for(...) {
if(matchFound) {
unsuccessful = false;
break;
}
}
if(unsuccessful) { print(...); }
也许您还应该考虑将变量重命名为 success
(至少对我来说这样更容易阅读):
boolean success = false;
for(...) {
if(matchFound) {
success = true;
break;
}
}
if(!success) { print(...); }
如您所见,您也不再需要 else
部分。
如果你使用Java8或以上,你可以进行以下操作,
Optional<Landing> landing = landings.stream().filter(i -> i.checkId(id)).findFirst();
landing.ifPresent(Landing::printLandings);
boolean unsuccessful = !landing.isPresent();
你也可以改进checkId方法如下,
public boolean checkId(int id) {
return this.landingId == id;
}
希望这能解决您的问题。干杯!
我想了解为什么我无法打印出我想要的结果。我已经更改了几次循环逻辑,但看不到问题。
我有一个数组列表ArrayList<Landing> landings = new ArrayList<>();
我在Landing
class中有以下方法查看登陆ID;
public boolean checkId(int id) {
if (this.landingId == id) {
return true;
} else {
return false;
}
}
我正在尝试创建一些输入处理,如果用户输入的 ID 与数组列表中的 ID 不匹配,则会打印一条错误消息。我似乎无法获得打印消息的失败场景
System.out.print("Please enter the landing ID: ");
int id = Integer.parseInt(sc.nextLine());
boolean unsuccessful = false;
for (int i = 0; i < landings.size(); i++) {
if (landings.get(i).checkId(id)) {
landings.get(i).printLandings();
unsuccessful = false;
break;
} else {
unsuccessful = true;
}
}
if (unsuccessful) {
System.out.println(
"\nThe ID you enterred does not match any landing");
}
break;
TIA
如果你想检查是否有“任何”(=至少一个)匹配,你必须从 boolean unsuccessful = true
.
我们来看最简单的情况:当List
为空时,循环不会运行一次。虽然 unsuccessful
不会改变并且必须在循环之前设置为 true
。
这是一个简化版本。
boolean unsuccessful = true
for(...) {
if(matchFound) {
unsuccessful = false;
break;
}
}
if(unsuccessful) { print(...); }
也许您还应该考虑将变量重命名为 success
(至少对我来说这样更容易阅读):
boolean success = false;
for(...) {
if(matchFound) {
success = true;
break;
}
}
if(!success) { print(...); }
如您所见,您也不再需要 else
部分。
如果你使用Java8或以上,你可以进行以下操作,
Optional<Landing> landing = landings.stream().filter(i -> i.checkId(id)).findFirst();
landing.ifPresent(Landing::printLandings);
boolean unsuccessful = !landing.isPresent();
你也可以改进checkId方法如下,
public boolean checkId(int id) {
return this.landingId == id;
}
希望这能解决您的问题。干杯!