读取文件时出现NumberFormatException错误

时间:2016-08-12 03:28:36

标签: java filereader numberformatexception

当我尝试从文本文件中读取一些数据并将其转换为整数时,我遇到了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);
    }

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

2 个答案:

答案 0 :(得分:0)

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

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

    totalBalNum = Double.parseDouble(holderStr);

答案 1 :(得分:0)

使用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);
相关问题