代码之家  ›  专栏  ›  技术社区  ›  user

标记字符串并转换为整数时发生NumberFormatException

  •  0
  • user  · 技术社区  · 8 年前

    我试图读入一个文本文件,并从该文件中找到行数和列数。我决定通过标记输入字符串,然后将其转换为整数来查找行和列。在编译时,我得到一个“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列。
    1 回复  |  直到 8 年前
        1
  •  0
  •   GKFX    8 年前

    您已经设置了不带分隔符的StringTokenizer(构造函数中为空字符串)。这意味着它无法将您的行拆分为代币。

    如果我明白你想做什么,你需要替换StringTokenizer代码(之后的一切 while((s = inF.readLine()) != null){ )带有

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

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