【发布时间】:2021-09-21 00:06:57
【问题描述】:
我有四个String[],其中包含一些单词并且长度不同。这些关键字在 txt 文件中进行搜索,如果找到一个单词,循环就会中断。问题是如果在第一个数组中找到单词,我该如何停止其他循环?就像如果在第一个数组中找到这个词,我希望另一个 for 循环中断,否则如果找不到这个词,那么我希望第二个循环进行迭代。我在嵌套 for 循环中尝试过,但我没有为我工作,因为我没有使用嵌套 for 循环。
这是我的代码:
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);
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);
break;
}
}
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);
break;
}
}
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);
break;
}
}
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);
break;
}
}
}
}
【问题讨论】:
-
有几个选项,但我看到的最 OOP 方式是责任链模式。至少,将其拆分为单独的方法。也许试试
String[][]。 -
您可以创建一个布尔值并将其设置为 false,如果您的字符串匹配,则将其设置为 true 并在每次进入新循环之前检查它。
-
@SaatvikRamani 所以我必须将这些循环包装到 while 循环中?
-
只使用二维数组。
-
@john - 不。只需将
for (...)重写为if (!flag) for(...),除了 he first 之外的所有循环。
标签: java arrays loops for-loop