从文件中的一行解析双精度时忽略字母

Nor*_*rsk 5 java double parsing

我正在尝试从文件中逐行导入一些数据。我要读取的一个特定行末尾可能有也可能没有“kB”(千字节),我想解析这一行中的双精度数,但我的程序给了我 java.lang.NumberFormatException。

    while(inputStream.hasNextLine())
    {
        inputStream.nextLine(); // Skips a line between each object
        String sn = inputStream.nextLine();
        String sa = inputStream.nextLine();
        double ss = Double.parseDouble(inputStream.nextLine()); // This is where the problem occurs
        int sd    = Integer.parseInt(inputStream.nextLine());
        addSong(sn, sa, ss, sd); // Send the four variables for Song() to the addSong method
    }
    inputStream.close();
Run Code Online (Sandbox Code Playgroud)

我有一种感觉,我可以在这里使用indexOf(),但我不确定如何使用。

干杯!

Mic*_*dan 5

double ss = Double.parseDouble(inputStream.nextLine().replaceAll("[a-zA-Z]", ""));
Run Code Online (Sandbox Code Playgroud)

这将帮助您从 AZ 中删除所有字符,无论情况如何。


Boh*_*ian 2

只需在阅读时删除该行中的所有非数字/点即可,方法是replaceAll("[^\\d.]", "")

double ss = Double.parseDouble(inputStream.nextLine().replaceAll("[^\\d.]", ""));
Run Code Online (Sandbox Code Playgroud)

这使其保持在一行。