Java 对于while if循环,如果未找到任何内容,则显示嵌套错误消息 String aaa=“密码”; int-wloop=0; while(wloop
您可以使用一个标志来设置“未找到密码”的状态,并根据该状态打印该语句。可能类似于以下内容:Java 对于while if循环,如果未找到任何内容,则显示嵌套错误消息 String aaa=“密码”; int-wloop=0; while(wloop,java,for-loop,if-statement,while-loop,Java,For Loop,If Statement,While Loop,您可以使用一个标志来设置“未找到密码”的状态,并根据该状态打印该语句。可能类似于以下内容: String aaa= "password"; int wloop = 0; while (wloop<myarraylist.size()) { for (int i = 0; i < myarraylist.size(); i++) {
String aaa= "password";
int wloop = 0;
while (wloop<myarraylist.size()) {
for (int i = 0; i < myarraylist.size(); i++) {
Something qwerty = myarraylist.get(i);
String bbb= qwerty.getinfor();
if (aaa.equals(bbb)) {
System.out.println("you have found it!");
wloop = myarraylist.size();
}wloop++;
}
System.out.println("nothing have been found");
}
String aaa=“密码”;
int-wloop=0;
布尔值isPasswordFound=false;
而在Java 8+中(wloop),您可以使用流
和anyMatch
来确定是否存在匹配。例如
String aaa= "password";
int wloop = 0;
boolean isPasswordFound = false;
while (wloop<myarraylist.size()) {
for (int i = 0; i < myarraylist.size(); i++) {
Something qwerty = myarraylist.get(i);
String bbb= qwerty.getinfor();
if (aaa.equals(bbb)) {
System.out.println("you have found it!");
isPasswordFound = true;
wloop = myarraylist.size();
}wloop++;
}
if(!isPasswordFound) {
System.out.println("nothing have been found");
}
}
在早期版本中,您需要一个标志。您不需要嵌套循环,但我希望每个循环都有一个。类似
if (myarraylist.stream().anyMatch(qwerty -> aaa.equals(qwerty.getinfor()))) {
System.out.println("you have found it");
} else {
System.out.println("nothing found");
}
这可能是一个解决方案。但我们真的需要两个循环吗?@Shubhandupramanik只提供问题的解决方案,而不是进行整个优化。感谢你们的帮助。任何观点都是有帮助的,因为我是九月份开始学习计算机科学的新学生。看到做某事的多种方法很有帮助。我必须学习sle现在是ep。但我对你的两个答案都投了赞成票。设置wloop=arraylist.size()
强制退出循环看起来像是在“欺骗”循环进入退出状态。当你可以使用简单的代码来明确你在做什么时,不要使用复杂的代码。在这种情况下,break
。谢谢!当我们学习循环时,课堂上没有告诉我们休息。现在我知道了。
boolean found = false;
for (Something qwerty : myarraylist) {
if (aaa.equals(qwerty.getinfor())) {
found = true;
break;
}
}
if (found) {
System.out.println("you have found it");
} else {
System.out.println("nothing found");
}