簡體   English   中英

無法從RandomAccessFile Java獲得正確的輸出

[英]Not getting proper output from RandomAccessFile java

這是我運行的代碼。

import java.io.*;
public class SETBQ1 {
  public static void main(String[] args) throws Exception {
    RandomAccessFile item = new RandomAccessFile("item.dat", "rw");
    String s;
    while ((s = item.readLine()) != null) {
      System.out.println(s);
    }
    System.out.println(s);
    item.close();
  }
}

順便說一句,item.dat的內容是

1 pencil 100 10
2 pen 200 5
3 eraser 5 1000
4 book 500 12

但是,我得到的輸出是

PS F:\tymalik\Malik\SEM 1\JAVA\ASS5> java SETBQ1
1 pencil 100 10
2 pen 200 5
3 eraser 5 1000
4 book 500 12
null

我想知道為什么最后一個值顯示的是空值而不是值? 在while循環之外處理字符串變量的解決方案是什么? 我將不勝感激。

最后的陳述

System.out.println(s);

顯示null因為它不在while循環的范圍內。 您可以在循環內分配另一個變量

String lastLine = null;
while ((s = item.readLine()) != null) {
    System.out.println(s);
    lastLine = s;
}
System.out.println(lastLine);

暫無
暫無

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

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