![](/img/trans.png)
[英]Buffer with bufferedreader.readLine () returns null unexpectedly
[英]Java's BufferedReader.readLine() behaving unexpectedly
我有一個文件,其中包含一些贊美詩的樂譜。 它應該由 Java 程序讀取,該程序會將這些贊美詩存儲為對象。 每首贊美詩都是這樣寫的:
1
Hallelujah
C
Rythm
C Am
I've |heard there was a |secret chord
$
'$' 只是 EOF 的標記。 我正在使用BufferedReader.readLine()
逐行讀取,直到“Rhytm”行初始化 Hymn object:
reader = new BufferedReader(new FileReader("/home/hal/teste.txt"));
String linha = "", titulo, r, t; int n;
while(linha!="$") {
n = Integer.parseInt(reader.readLine()); //reading the number
titulo = reader.readLine(); //reading the title
Tom tom = new Tom(reader.readLine()); //reading the tone
Ritmo ritmo = new Ritmo(reader.readLine()); //reading the rythm
Hino hino = new Hino(n, titulo, tom, ritmo); //initializing the object
然后我只是分別閱讀每一行。 問題是,第一個readLine()
執行時,它讀取的是第六行(“ C Am
”),而不是第一行(“ 1
”)。 我嘗試使用Scanner.nextInt()
來獲取該數字,但它給了我同樣的錯誤。 那是我的控制台的 output:
Exception in thread "main" java.lang.NumberFormatException: For input string: " C Am"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:638)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at project/project.Build.main(Build.java:22)
Build.java:22
是其中n = Integer.parseInt(reader.readLine());
位於。 我究竟做錯了什么?
只有文件的第一行包含 integer,因此不應在 while 循環中解析它。
在循環中,您應該只處理可重復的行。 正如@Fureeish 提到的,您還需要使用等號比較字符串。
通常解析行看起來像這樣:
for (String linha = reader.readLine(); linha != null && !linha.equals("$"); linha = reader.readLine()) {
...
}
使用這個 for 循環,您可以逐行遍歷文件。 在循環中,您應該處理不同的可能性。
最好的方法可能是在循環外處理前 4 行,然后在其中包含三個不同的情況:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.