有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

读取文件时发生java 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) 个答案

  1. # 1 楼答案

    好的,我认为将字符串转换为整数,然后将其类型转换为double会导致错误。为什么不把字符串转换成double呢。 此外,阅读时必须修剪线条,以避免出现空格

        String holderStr = br.readLine().trim();
        System.out.println(holderStr);
    
        totalBalNum = Double.parseDouble(holderStr);
    
  2. # 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);