【问题标题】:NumberFormatException when tokenizing a string and converting to an integer标记字符串并转换为整数时出现 NumberFormatException
【发布时间】:2016-05-03 16:35:10
【问题描述】:

我正在尝试读取文本文件并从该文件中查找行数和列数。我决定通过标记输入字符串然后将其转换为整数来查找行和列来做到这一点。当我编译时,我得到一个“java.lang.NumberFormatException.forInputString”。任何解释为什么会导致此问题将不胜感激。谢谢。

BufferedReader inF = new BufferedReader(new FileReader(new File("/Users/marco/Desktop/5ele.txt")));
    String s = "";

    int row = 0;
    int col = 0;
    int z = 0;

    while((s = inF.readLine()) != null){  

        StringTokenizer st = new StringTokenizer(s, ""); 
        while(st.hasMoreTokens()){
            int convertedToInt = Integer.parseInt(st.nextToken());   //this is where the problem occurs

            if (z == 0) {
                row = convertedToInt;
            } else if (z == 1) {
                col = convertedToInt;
            }

            z++;
        }
    }
  • 我还链接了一个文本文件的示例: Sample Text File

  • 请注意,每个字符(无论是句点还是字母)都可以想象为表格中的单个单元格

  • 我在文本文件示例中查找的输出是 3 行 10 列。

【问题讨论】:

  • 您将整行解析为Integer.parseInt() 的输入,因为您使用的是new StringTokenizer(s, "");,其中分隔符是一个空字符串。
  • 我应该如何解决这个问题?
  • 您究竟是什么意思将此输入解析为整数?您可以使用您提供的示例输入的解析结果来编辑您的问题吗?
  • 您的原始文件是什么样的?显示几行

标签: java token bufferedreader numberformatexception stringtokenizer


【解决方案1】:

您已经设置了没有分隔符的 StringTokenizer(构造函数中的空字符串)。这意味着它不能将您的线路拆分为标记。

如果我理解您要执行的操作,您需要将 StringTokenizer 代码(while((s = inF.readLine()) != null){ 之后的所有内容)替换为

  z++;
  col = s.length()
}
row = z;

这使用 z 来计算循环的行数,并从字符串长度中获取列数。

【讨论】:

  • 不客气;请将此答案标记为已接受。当然,像我这样一遍又一遍地设置col 是草率的;您应该检查 s.length() 是否始终具有相同的值。
猜你喜欢
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 2012-06-20
  • 2019-10-31
  • 2019-01-10
  • 1970-01-01
  • 2016-08-07
  • 2015-09-03
相关资源
最近更新 更多