【问题标题】:Java NumberFormatException while reading阅读时出现 Java NumberFormatException
【发布时间】:2016-10-21 06:21:34
【问题描述】:

这是我编写的代码的一部分。 阅读器似乎读取了第一个字符串“2”,但由于某种原因它没有将其转换为整数。

public void fileinput2() 
{
try 
{
        BufferedReader file=new BufferedReader(new FileReader("ddv.txt"));
        try 
{
            while((line=file.readLine())!=null){
                String[] s=line.split("\\t+");
                int firstindex=Integer.parseInt(s[0].trim());
                int secondindex=Integer.parseInt(s[1].trim());
                                    adj[firstindex-1][secondindex-1]=1;
                adj[secondindex-1][firstindex-1]=1;
                                    /*for(int i=0;i<s.length;i++)
                                    {System.out.println(s[i]);
                                    int x=Integer.valueOf(s[i].trim());
                                    }*/

                }
        } catch (NumberFormatException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

DDV 是一个文本文件,如下所示:

2    8
6    9
4    10

等等。

但是我得到了这个错误

java.lang.NumberFormatException: For input string: "2"
at       
    java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)

at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615).

请帮帮我谢谢。:)

【问题讨论】:

标签: java exception exception-handling


【解决方案1】:

它不是真正的“2”,您在“2”之前有不可打印的符号 \uFEFF。它在您的文件中是不可见的 utf-8 前缀

您可以分析文件的第一个字符,或者只是添加惰性 s.replace("\uFEFF", "") 或使用正则表达式解析行

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多