Java中满足匹配条件时如何终止多个非嵌套for循环
解决方法
你现有代码的问题是break只会终止当前所在的单层循环,所以第一个数组查到匹配项后,后面三个数组的循环还是会依次执行,以下是两种可直接落地的实现方案:
方案1:新增匹配状态标记
新增布尔变量标记是否已经找到匹配项,每个数组遍历前先判断状态,未找到才执行遍历:
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; public class practice { static String wfound; public static void main(String[] args) throws IOException { String a[] = { "universe", "world", "html" ,"name"}; String b[] = { "animal", "Bird", "HTML" }; String c[] = { "choclate", "HTML", "hello" }; String d[] = { "css", "side"}; String file= new String(Files.readAllBytes(Paths.get("D://test1.txt")), StandardCharsets.UTF_8); // 新增匹配状态标记,默认未找到 boolean hasFound = false; for (String an : a) { Pattern p = Pattern.compile("\\b" + an + "\\b", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(file); if (m.find()) { wfound = an; System.out.println("In array 1: " + an); hasFound = true; break; } } // 只有未找到才执行下一个数组的遍历 if (!hasFound) { for (String ab : b) { Pattern p = Pattern.compile("\\b" + ab + "\\b", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(file); if (m.find()) { wfound = ab; System.out.println("In array 2: " + ab); hasFound = true; break; } } } if (!hasFound) { for (String ac : c) { Pattern p = Pattern.compile("\\b" + ac + "\\b", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(file); if (m.find()) { wfound = ac; System.out.println("In array 3: " + ac); hasFound = true; break; } } } if (!hasFound) { for (String ad : d) { Pattern p = Pattern.compile("\\b" + ad + "\\b", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(file); if (m.find()) { wfound = ad; System.out.println("In array 4: " + ad); hasFound = true; break; } } } } }
方案2:优化重复代码+标签跳出
四个数组的遍历逻辑完全一致,可以把它们打包成二维数组统一遍历,配合Java的带标签break直接跳出外层循环,代码更简洁易维护:
import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.regex.Matcher; import java.util.regex.Pattern; public class practice { static String wfound; public static void main(String[] args) throws IOException { String a[] = { "universe", "world", "html" ,"name"}; String b[] = { "animal", "Bird", "HTML" }; String c[] = { "choclate", "HTML", "hello" }; String d[] = { "css", "side"}; // 把四个数组按优先级打包成二维数组 String[][] allKeywords = {a, b, c, d}; String file= new String(Files.readAllBytes(Paths.get("D://test1.txt")), StandardCharsets.UTF_8); // 给外层循环加标签 search: for (int i = 0; i < allKeywords.length; i++) { String[] currentArr = allKeywords[i]; for (String keyword : currentArr) { Pattern p = Pattern.compile("\\b" + keyword + "\\b", Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(file); if (m.find()) { wfound = keyword; System.out.println("In array " + (i+1) + ": " + keyword); // 直接跳出外层的search循环,所有遍历直接终止 break search; } } } } }
后续如果新增关键词数组只要往allKeywords里追加即可,不用重复写循环逻辑。
内容的提问来源于stack exchange,提问作者john
相关产品推荐
相关产品推荐

