我有一个文件,其中包含一些赞美诗的乐谱。应该由将这些赞美诗存储为对象的Java程序读取。每个赞美诗都这样写:
1
Hallelujah
C
Rythm
C Am
I've |heard there was a |secret chord
$
'$'只是EOF的代币。我正在使用BufferedReader.readLine()
逐行读取,直到'Rhytm'行初始化Hymn对象:
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()
来获取该数字,但这给了我同样的错误。那是我控制台的输出:
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());
的位置。我在做什么错?
仅文件的第一行包含一个整数,因此不应在while循环内解析它。
在循环中,您只应处理可重复的行。正如@Fureeish所提到的,您还需要使用等于来比较字符串。
通常解析行看起来像这样:
for (String linha = reader.readLine(); linha != null && !linha.equals("$"); linha = reader.readLine()) {
...
}
使用此for循环,您逐行遍历文件。在循环中,您应该处理各种可能性。
最好的方法可能是处理循环外的前4行,然后在其中包含三种不同的情况: