我继续在代码中获取NumberFormatException,但我似乎无法弄明白为什么。
import java.io.*;
import java.util.*;
public class SongCollection
{
ArrayList<Song> songs;
public SongCollection(ArrayList<Song> songs) {
this.songs = songs;
}
public void addSong(String line) {
String[] parts = line.split("\t");
int year = Integer.parseInt(parts[0]);
int rank = Integer.parseInt(parts[1]);
String artist = parts[2];
String title = parts[3];
Song addedSong = new Song(year, rank, artist, title);
songs.add(addedSong);
}
public void printSongs(PrintStream output) {
for (int i = 0; i < songs.size(); i++) {
Song song = songs.get(i);
output.println(song.toString());
}
}
}
我用于addSong方法的字符串来自this输入文件:
我得到的错误是&#34; java.lang.NumberFormatException:对于输入字符串&#34; 1965&#34; (在java.lang.NumberFormatException中)&#34;
感谢您的帮助!
答案 0 :(得分:-1)
your input "1965" doesn't contain "\t". so the value of line will be 1965,
int year = Integer.parseInt(parts[0]);
parts[0] will have 1965 value, and it will be complied successfully, but
int rank = Integer.parseInt(parts[1]);
part [1]将没有任何东西,因此会发生NumberFormatException,请确保您的输入应包含&#39; \ t&#39;字符和数字,以便部分[0]和部分[1]的值应为数字。
答案 1 :(得分:-1)
我明白为什么我一直都会收到错误。我需要从文件中删除BOM,因为我使用记事本打开它。现在一切正常,感谢所有的帮助!