【问题标题】:NumberFormatException error from reading a file读取文件时出现 NumberFormatException 错误
【发布时间】:2016-08-12 03:28:36
【问题描述】:

当我尝试从文本文件中读取一些数据并将其转换为整数时,我收到了NumberFormatException 错误。根据我看到其他人的说法,此错误是在使用pasreInt() 将空字符串转换为整数时引起的。但是我已经能够将文件中的字符串“1”打印到输出中。有谁知道为什么我得到这个错误,即使字符串似乎不是空的?这是我的代码:

try {
        //Retrieve Info
        FileReader fr = new FileReader("BankInfo.txt");
        BufferedReader br = new BufferedReader(fr);
        //Skip specified number of lines
        for(int i=0; i<line; i++) {
            br.readLine();
        }

        //Print the string to output
        String holderStr = br.readLine();
        System.out.println(holderStr);

        //The line creating the NumberFormatException
        totalBalNum = (double)Integer.parseInt(holderStr);

        br.close();
        //Read Whole File
        BufferedReader br2 = new BufferedReader(fr);
        while((str = br.readLine()) != null) {
            arrList.add(str);
        }
        br2.close();
    } catch (IOException | NumberFormatException e) {
        System.out.println("ERROR! Problem with FileReader. " + e);
    }

我知道我的代码可能真的很草率而且效率低下......我有点菜鸟。

【问题讨论】:

  • 在通过之前尝试holderStr.trim(),你为什么要再次投射到 Double ?你的字符串中可能还有一些额外的字符,所以这些可能是NumberFormatException的原因
  • 只是为了清楚变量“totalBalNum”是整数还是双精度数?
  • 能否提供异常的Stacktrace?
  • @Deepak totalBalNum 是双精度数。我已经对此进行了试验,并将其转换为双精度不会导致错误。修剪字符串也不起作用。

标签: java filereader numberformatexception


【解决方案1】:

好的,我认为将字符串转换为整数然后将其类型转换为双精度会导致错误。为什么不将字符串转换为双精度。 此外,您必须在阅读时修剪线条以避免任何空格。

    String holderStr = br.readLine().trim();
    System.out.println(holderStr);

    totalBalNum = Double.parseDouble(holderStr);

【讨论】:

  • 是的!这就是问题所在。此外,直到现在我才知道 Double.parseDouble 存在 xD,就像我说我有点菜鸟一样。感谢您的帮助。
  • 很高兴,我能帮上忙。
【解决方案2】:

使用replaceAll() 将除数字以外的所有内容都转换为空字符。

holderStr.replaceAll("\\D+","");

例如。

字符串extra34345 dfdf 将被转换为34345
字符串ab34345ba 将转换为34345
字符串\n34345\n 将转换为34345

代码

String holderStr = br.readLine();

//this line will remove everything from the String, other than Digits
holderStr= holderStr.replaceAll("\\D+","");

System.out.println(holderStr);

【讨论】:

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