[英]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.