gpt4 book ai didi

Java:将字符串解析为 double

转载 作者:行者123 更新时间:2023-11-29 09:40:20 25 4
gpt4 key购买 nike

我正在将一个文件读入一个数组并尝试取出数字并将它们作为 double 放入它们自己的数组中。显然我的中间名一定是“Error”。据我所知,代码没问题……至少没有什么让我感到意外的。这是它的全部荣耀。

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
import java.lang.Object.*;

public class ReadFromFile {
public static void main (String[] args){
File file = new File("vector10.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
StringBuffer sb = new StringBuffer();
String string = new String();

try{
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);


while((string=dis.readLine()) != null){
sb.append(string+"\n");
}

fis.close();
bis.close();
dis.close();

System.out.println(sb);
String newString = sb.toString();
System.out.println(newString);
String[] doubles = newString.split(",");
for (int i=0; i<doubles.length; i++){
System.out.println(doubles[i]);
}

Double arrDouble[] = new Double[doubles.length];

int idx = 0;
for(String s : doubles) {
arrDouble[idx++] = Double.parseDouble(s);
}

} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

一直报错

at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:412)
at java.lang.Long.parseLong(Long.java:461)
at ReadFromFile.main(ReadFromFile.java:51)

编程不一定是我的强项,看着屏幕我的眼睛开始流血。任何想法或提示都将不胜感激。干杯

最佳答案

如果您的文件是逗号分隔的,那么最好使用 Scanner

String doubles = "1.25,    1.65, 1.47";

Scanner f = new Scanner(doubles);
f.useLocale(Locale.US); //without this line the program wouldn't work
//on machines with different locales
f.useDelimiter(",\\s*");

while (f.hasNextDouble()) {
System.out.println(f.nextDouble());
}

关于Java:将字符串解析为 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1418524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com