我有一个代码,其中有一个按钮,用于获取文本字段的输入,然后查看 .txt 文件,看看是否有匹配项。唯一的问题是它会遍历每一行并检查该行是否匹配,这意味着 if 和 else 语句都会被触发。假设 .txt 文件有 3 行,分别为 1234 、 5423 、 8543 ,然后输入为 1234 ,然后代码按照 if 语句的预期运行,因为输入与预期匹配。但随后它继续下去,因此它也触发了不应该的 else 语句。
这是我的代码
public static String input = "";
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String input = jTextField1.getText();
File file =new File("file.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains(input)){
popUp1 pu1 = new popUp1();
pu1.setVisible(true);
} else {
popUp2 pu2 = new popUp2();
pu2.setVisible(true);
}
}
} catch (FileNotFoundException e) {
System.out.println("Error");
}
}
最佳答案
你的做法是错误的。正如您所注意到的,如果文件中的行与输入不匹配,则会触发“失败”处理。相反,您需要遍历整个文件,检查匹配的行,如果找到匹配的行,则触发该行为,然后终止循环。仅当您检查完文件但仍未找到匹配项时,才应触发“失败”行为:
boolean found = false;
while(!found && in.hasNext()) {
String line = in.nextLine();
if (line.contains(input)) {
found = true;
popUp1 pu1 = new popUp1();
pu1.setVisible(true);
}
}
// If we've gone over the entire file and still not found anything:
if (!found) {
popUp2 pu2 = new popUp2();
pu2.setVisible(true);
}
关于java - if else 语句没有停止问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41093816/