尽管修剪,我怎么能避免这种格式异常

时间:2016-01-20 21:51:05

标签: java arrays parsing

编辑:隐藏的角色与我的编辑混乱。

我想从我的文本文件中读取并从中添加对象到数组中。我得到了一个

NumberFormatException: For input string : "2".  

如果删除文件的第一行,我会得到输入字符串“3”的格式异常。

我在那里错过了什么?

ArrayList<Personne> listp = new ArrayList<Personne>();
try {
    FileReader file = new FileReader(personneFilePath);
    Scanner sc = new Scanner(file);
    while (sc.hasNextLine()) {
        String line = sc.nextLine();
        String[] attributes = line.split(",");
        listp.add(new Personne(Integer.parseInt(attributes[0].trim()), attributes[1], attributes[2], Double.parseDouble(attributes[3]), attributes[4], attributes[5], attributes[6]));
    }
    file.close();
} catch (FileNotFoundException e) {
    System.out.println("Erreur 1 : " + e.getMessage());
} catch (IOException e) {
    System.out.println("Erreur 2 : " + e.getMessage());
}

以下是我正在阅读的文件的内容;

2, Claire, Chazal, 65.0 , rue de Rennes, Laval, 53000
3, Jacques, Dupont, 90.0 , rue des Anges, Paris, 75000
4, Celine, Dia, 66.0 , rue Diderot, Paris, 75000
5, Remy, Cheval, 88.0 , rue du paradis, Nantes, 44000

2 个答案:

答案 0 :(得分:0)

你在做什么看起来很好。

我建议使用调试模式(IntelliJ或Eclipse可以很好地工作)并使用Integer.parseInt方法查看它获得的输入或失败的位置。

或者,添加print语句以查看attributes[0].trim()的值,也可以是字符串的长度。似乎可能存在不可打印的角色。

答案 1 :(得分:0)

它像你的文件包含2附近的一些不可打印的字符,这不是空白,所以trim()无法删除它。

要删除它,您可以使用replaceAll("\\D","")代替trim()

更好的首选解决方案是删除此问题的原因,因此请正确设置编辑器/文件格式/编码并停止将这些字符放在您的文件中。