[英]Java: Parsing a string to a double
我正在将文件读取到数组中,并尝试取出数字并将它们作为自己数组中的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());
}
也许您可以尝试使用Scanner类?
Scanner sc = new Scanner(new File("vector10.txt"));
ArrayList<Double> lst = new ArrayList<Double>();
while (sc.hasNextDouble()) {
lst.add(new Double(sc.nextDouble()));
}
您的代码似乎并不是实际运行的代码,但是在您的代码中,您正在构建一个包含所有数字的大字符串,并用换行符分隔。 但是然后您将其分割(使用String.split),并以逗号分隔,并且该字符串中没有逗号。 因此Double.parseDouble一次获取所有数字。
该错误表明您正在调用Long.parseLong(),而不是Double.parseDouble(),就像您发布的代码所说的那样。 也许您忘记了重新编译?
那可能是整个问题,但如果不发送该值的System.out.println(string),您将在此之前调用Double.parseDouble(string),这样您就可以看到失败的值。
像所有parse*
方法一样, Double.parseDouble()
对它们不期望的字符的反应也不好,不幸的是,它包含空格。 字符串中的一些空格会破坏您的一整天。
为了解决这个问题,首先也要在空格上进行split
,因此像newString.split("[,\\\\s]+")
这样的方法可以通过拆分和删除任何空白和/或空格来很好地工作。逗号。 然后,当您尝试解析时,为安全起见, trim
字符串Double.parseDouble(doubles[i].trim())
类似于Double.parseDouble(doubles[i].trim())
。 为了提高安全性,请在分析之前检查修剪后的字符串是否不是空字符串-可能类似于if (doubles[i].trim().length() < 1) continue;
。
祝好运。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.