如何跳出嵌套循环?
我有一种方法来比较两个对象列表。
两个列表中的对象都是唯一的。
我使用 2 级嵌套 for 循环来完成此操作,
如果两个对象正确匹配,我想终止内部 for 循环的剩余循环。
Java 中是否可以终止 for 循环的剩余迭代?
谢谢
示例代码:
public class NestedForLoops {
public static void main(String[] args) {
String one = "abcdefgh";
String two = "ijkhmnop";
System.out.println(nestedForLoop(one, two));
}
public static String nestedForLoop(String one, String two)
{
String res = "";
for(int i = 0; i < one.length(); i++)
{
for(int j = 0; j < two.length(); j++)
{
if(one.charAt(i) == two.charAt(j)){
System.out.println(i + " " + j);
res += one.charAt(i);
continue;
}
}
}
return res;
}
}
I have a method to compare two list of objects.
The objects are unique in both lists.
I doing it with 2 level nested for loops
I want to terminate the inner for loop's remaining cycles if two objects match correctly.
Is it possible to terminate the remaining iteration of a for loop in Java?!
Thanks
The Sample Code:
public class NestedForLoops {
public static void main(String[] args) {
String one = "abcdefgh";
String two = "ijkhmnop";
System.out.println(nestedForLoop(one, two));
}
public static String nestedForLoop(String one, String two)
{
String res = "";
for(int i = 0; i < one.length(); i++)
{
for(int j = 0; j < two.length(); j++)
{
if(one.charAt(i) == two.charAt(j)){
System.out.println(i + " " + j);
res += one.charAt(i);
continue;
}
}
}
return res;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
中断内部:
中断外部 for 循环:
Break inner:
Break outer for loop:
在内部循环中使用
break;
语句。如果您还想终止外部标签,则必须给外部标签一个标签并使用break label;
。use the
break;
statement in the inner loop. If you want to terminate the outer one as well, you'd have to give the outer one a label and usebreak label;
.是的。只需放置一个 if 语句来检查两个对象是否匹配,并在 if 中放置一个 break 语句。这是代码示例:
Yes it is. Just put an if statement that checks for a match of the two objects, and within the if, put a break statement. Here's the code sample:
标签有效(正如已经回答的那样)
如果该方法确实做到了这一点,请检查是否相等,那么您也可以在对象匹配时从该方法返回,看起来像一个足够小的方法,不会使返回成为一种不好的做法。就我个人而言,我发现这比使用标签更具可读性。
Labeling works (as already replied)
If the method does exactly that, check for equality, then you could also just return from the method when the objects match, looks like a small enough method to not make returning a bad practise. Personally I'd find that more readable than using labels.
使用多级中断:
或者,创建一个单独的方法并使用
return
而不是break
应该更具可读性,因为 return 语句更为常见。Use a multi-level break:
Alternatively, creating a separate method and using
return
instead ofbreak
should be more readable, since return statements are far more common.