簡體   English   中英

訪問值While While循環

[英]Access value Outside While loop

我正在讀取整個文件,如果它包含特定字符串,我想使用該行。 我無法使用該字符串,因為它在while循環之外打印為null ,盡管事實上我已經在循環外部初始化它。

FileInputStream wf = new FileInputStream(pr.getSplitDir() + listfiles[i]);
BufferedReader wbf = new BufferedReader(new InputStreamReader(wf));
String wfl = "";
while ((wfl = wbf.readLine()) != null) {
    if (wfl.contains("A/C NO:")){
        // System.out.println(wfl); // Here it is Printing the correct line
    }
}
System.out.println(wfl); // Here it is printing null

請幫忙。

嘗試下面這個,你必須使用另一個String或StringBuilder來獲得最終輸出

     FileInputStream wf = new FileInputStream(pr.getSplitDir() + listfiles[i]);
        BufferedReader wbf = new BufferedReader(new InputStreamReader(wf));
        String wfl = "";
        StringBuilder sb = new StringBuilder();
        while ((wfl = wbf.readLine()) != null) {
            if(wfl.contains("A/C NO:")){
                //System.out.println(wfl);//Here it is Printing the correct line
                sb.append(wfl);
            }
        }
        System.out.println(sb.toString());//Here it is printing null
 while ((wfl = wbf.readLine()) != null) {
                if(wfl.contains("A/C NO:")){
                    //System.out.println(wfl);//Here it is Printing the correct line

                }
            }

只有當wfl is null時,你的while循環才會退出 所以你有答案!

因為你的wbf.readLine讀取為null時,它也會分配wfl,然后比較為null

while ((wfl = wbf.readLine()) != null) {  // here wbf.readLine when read null assigns to wfl
  if(wfl.contains("A/C NO:")){
        //System.out.println(wfl);//Here it is Printing the correct line
     }
 }

這樣做,如果你想循環打印,

String test ="";
String wfl ="";
while ((wfl = wbf.readLine()) != null) {
      if(wfl.contains("A/C NO:")){
            //System.out.println(wfl);//Here it is Printing the correct line
      }

      test = test + wfl ; // for assigning all line
      //test = wfl // for assigning last line
}



 System.out.println(test); // it wil print the correct line

要停止,你的循環需要wflnull ,所以當你的循環剛剛停止時, wfl顯然是null

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM