【问题标题】:Number Format Exception While Reading A File读取文件时出现数字格式异常
【发布时间】:2015-04-19 18:01:09
【问题描述】:

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

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());

【问题讨论】:

  • 只是一个忠告,因为看起来您可能需要从这个文件中读取多行。我建议一次将所有行读入List<String>。请参阅最佳答案here 中提供的第二种非常紧凑的方法。
  • 感谢@Will 的关心,实际上我忽略了 3 之后的空格。

标签: java parsing parseint


【解决方案1】:

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

您应该在解析为 int 之前消除空格:

 int number = Integer.parseInt(sr.readLine().trim());

【讨论】:

  • 如果您认为该问题在某些方面可能有用并且可以帮助某人投票,请:)
猜你喜欢
  • 1970-01-01
  • 2016-04-07
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-27
相关资源
最近更新 更多