[英]How to use variable in a while loop outside of the loop in java?
我有一个在while循环中设置的变量,因为它是从文件中读取的。 我需要访问和使用循环外部的代码,因为我在if语句中使用变量而if语句不能在while循环中,否则它将重复多次。 这是我的代码。
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\Brandon\\Desktop\\" + Uname + ".txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}if(sCurrentLine.contains(pwd)){System.out.println("password accepted");}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
将if语句放在for循环中,但使用break:
while...
if(sCurrentLine.contains(pwd)){
System.out.println("password accepted");
break;
}
这会打破for循环,这样一旦找到密码,它就会停止循环。 你不能真正在循环之外移动if-check,因为你想检查每一行的密码,直到找到它,对吧?
如果这样做,则无需将sCurrentLine
变量移出循环。 如果要执行sCurrentLine.equals(pwd)
而不是使用contains
也可能需要进行sCurrentLine.equals(pwd)
。
您已经在while循环之外声明了sCurrentLine
。 问题是你一直在下一行继续使用它。 如果你仍然希望它打印文件,你要做的是记住找到了密码或找到了它的代码:
BufferedReader br = null;
boolean pwdFound = false;
String pwdLine = "";
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\Brandon\\Desktop\\" + Uname + ".txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
if(sCurrentLine.contains(pwd)){
System.out.println("password accepted");
pwdFound = true;
pwdLine = sCurrentLine;
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
boolean flag = false; while((sCurrentLine = br.readLine())!= null){
if(sCurrentLine.contains(pwd))
{
flag = true;
break;
}
} if(flag){System.out.println(“password accepted”);}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.