读取文件时的数字格式异常

时间:2015-04-19 18:01:09

标签: java parsing parseint

在读取文件内容时出现以下错误,我认为我的代码没有正确地将其转换为整数以下是错误:

Exception in thread "main" java.lang.NumberFormatException: For input string: "3 "
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Program.main(Program.java:192)

这是代码:

    FileReader fin = new FileReader("task.txt");
    BufferedReader sr = new BufferedReader (fin);
    int count = 0;
    int number = Integer.parseInt(sr.readLine());

1 个答案:

答案 0 :(得分:4)

您正在尝试解析包含空格和数字的字符串 - "3 "

在解析为int之前你应该删除空格:

 int number = Integer.parseInt(sr.readLine().trim());
相关问题