2012-04-11 51 views
1

我有这样的规定,使用适当的getter和setter方法的类...加载CSV文件,并从价值创造新的类实例

public class Album { 
    private int id; 
    private String artist; 
    private String name; 
    private int published; 
} 

我也有存储此.csv文件一些相册的内容。在该文件中,一行代表一个专辑。

我试图从.csv文件中读取信息,然后使用Album类的setters分配值。这里是我的代码...

public Map<Integer, Album> load() { 

    Scanner scanner = new Scanner(fileName); 
    Map<Integer, Album> loadedAlbums = new HashMap<Integer, Album>(); 

    while(scanner.hasNextLine()) { 
     Album album = new Album(); 

     String[] albumDivided = scanner.nextLine().split(","); 
     //in the .csv file every unit of information is divided by a comma. 

     album.setId(Integer.parseInt(albumDivided[0])); //this is line 11. 
     album.setArtist(albumDivided[1]); 
     album.setName(albumDivided[2]); 
     album.setPublished(Integer.parseInt(albumDivided[3])); 

     loadedAlbums.put(album.getId(), album); 

    } 

    return loadedAlbums; 
} 

但是,试图利用这个代码,我得到以下异常:

java.lang.NumberFormatException:对于输入字符串: “albums.csv” 在第11行。

请你帮我理解这个问题的原因。

+0

哦,该文件中信息的格式为:“1,歌手名,专辑名,发表” – Mark 2012-04-11 13:26:11

回答

1

那么这个问题是由异常描述你...

一个NumberFormatException会被你Integer.parseInt()线之一触发。触发异常的代码行是第11行(根据异常消息) - 不确定哪一行是这种情况,但可能是第一行Integer.parseInt()行。

你的代码试图将“albums.csv”的值转换为一个数字,这显然不是。因此,您的CSV文件中的某处必须有一行,其中包含值albums.csv其中期望有一个数字。

希望这有助于查明问题。

+0

谢谢,我现在意识到这个问题。 – Mark 2012-04-11 13:41:14

1

既然你不想在这里,整个解决方案是解决问题的提示:

你应该看看API documentation of the Scanner class。仔细看看期望单个String参数的构造函数(如在代码中使用它)。

+0

感谢您的帮助。在将来更仔细地学习API – Mark 2012-04-11 13:41:31

1

据我所知,albumDivided [0]将包含“1”。由于点而无法解析为整数。从csv文件中删除点,或者在将其解析为Integer之前创建一个删除点的新字符串。该方法可能是这个样子:

String newString; 
for(int i=0;i<albumDivided[0].length-1;i++){ //length -1 to remove the dot 
    newString = newString + albumDivided[0].charAt(i); //get the string stored in albumDivided[0] and add each char to the new string 
} 
+0

谢谢,如果我遇到问题,我会记住这一点。 – Mark 2012-04-11 13:59:38

相关问题