java 将字符串从缓冲读取器转换为双精度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17196283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:16:42  来源:igfitidea点击:

Converting string from buffered reader to double

java

提问by Tziyhi Choo

my assignment requires me to create an program to read an text file and calculate the values in there. The text file contain something like this :

我的作业要求我创建一个程序来读取文本文件并计算其中的值。文本文件包含如下内容:

"11047461 [tab] 60.5

 12024121 [tab] 58

 12027019 [tab] 33"

the 8 numbers infront is ignore, only the numbers at the back are calculated.

前面的8个数字被忽略,只计算后面的数字。

after refering to some codings from this web.I still get a message like this :

在参考了这个网站的一些编码后,我仍然收到这样的消息:

Exception in thread "main" java.lang.NumberFormatException: For input string: "11047461 60.5"
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
    at java.lang.Double.parseDouble(Double.java:510)
    at Problem2.main(Problem2.java:16)


public static void main(String[] args) throws IOException, FileNotFoundException {
    // TODO Auto-generated method stub
    BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream("C:\Users\My World\Downloads\PRG102D.txt")));

    String line;
    double score;

    while((line = read.readLine()) != null) {
    score = Double.parseDouble(line);
    System.out.println(score);


}

}

回答by Chris Gerken

You only want to parse the part of the line that contains the String representation of the double value. As it is, you're parsing the entire line without ignoring the first number.

您只想解析包含 double 值的 String 表示形式的行部分。实际上,您正在解析整行而不忽略第一个数字。

回答by android developer

your problem is that you didn't parse the line, so it tries to decode the entire line to a double, and it can't.

您的问题是您没有解析该行,因此它尝试将整行解码为双精度值,但它不能。

here's something you can do :

这是你可以做的事情:

while((line = read.readLine()) != null) 
    {
    score = Double.parseDouble(line.subString(lastIndexOf(' ')+1));
    System.out.println(score);
    }