【问题标题】:NumberFormatException being thrown by Integer.parseInt()Integer.parseInt() 抛出 NumberFormatException
【发布时间】:2013-11-08 21:28:14
【问题描述】:

对于我的任务,我正在尝试将整数序列读入数组并计算有关数组的一些内容。我被限制使用 InputStreamReader 和 BufferedReader 从文件中读取,并且 Integer.parseInt() 在第一行读取后抛出 NumberFormatException。

如果我通过键盘单独输入每个数字,一切正常,但如果我尝试直接从文件中读取,则根本不起作用。

这是目前为止的代码

int[] array = new int[20];

    try {
        int x, count = 0;
        do{
            x = Integer.parseInt((new BufferedReader(new InputStreamReader(System.in)).readLine()));
            array[count] = x;
            count++;
        }
        while (x != 0);
    }
    catch (IOException e){
        System.out.println(e);
    }
    catch (NumberFormatException e){
        System.out.println(e);
    }

要测试的案例是

33
-55
-44
12312
2778
-3
-2
53211
-1
44
0

当我尝试复制/粘贴整个测试用例时,程序只读取第一行然后抛出 数字格式异常。为什么 readLine() 只读取第一个值而忽略其他所有值?s

【问题讨论】:

  • BufferedReader 实际上并没有抛出 NumberFormatException,它是同一行上的另一种方法。如果您进一步阅读堆栈跟踪(您尚未提供 - 请在未来涉及 Java 异常的问题中提供堆栈跟踪),您应该能够看到这一点。
  • 啊,我看到你隐藏了堆栈跟踪,难怪你看不到它。永远不要这样做:System.out.println(e)。相反,请e.printStackTrace() - 或者干脆完全摆脱捕获 - 它可能不需要。

标签: java


【解决方案1】:

您每次都在重新打开System.in。我不知道这是做什么的,但我认为它不会很好。

相反,您应该使用 one BufferedReader,并在您的循环中,从中逐行读取。

【讨论】:

    【解决方案2】:

    我认为发生这种情况的方式是您创建一个阅读器,读取一行,然后在下一次迭代中创建一个新的,它是空的,但仍试图读取,因此它读取“”,通过它发送给解析器,Integer.parseInt() 抛出 NumberFormatException 因为它无法解析。正确的做法是:

    int[] array = new int[20];
    
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            int x, count = 0;
            do {
                String s = reader.readLine();
                x = Integer.parseInt(s);
                array[count] = x;
                count++;
            }
            while (x != 0);
        } catch (IOException | NumberFormatException e) {
            e.printStackTrace();
        }
    

    【讨论】:

      猜你喜欢
      • 2012-11-25
      • 1970-01-01
      • 2017-03-11
      • 2015-07-16
      • 2017-01-26
      • 2011-01-16
      • 1970-01-01
      • 2013-03-29
      • 2020-06-12
      相关资源
      最近更新 更多