提问人:Erik 提问时间:9/8/2020 更新时间:9/8/2020 访问量:561
Java:更改 scanner.nextDouble 接受点作为小数分隔符或在文件中使用逗号写入 double
Java: Changing scanner.nextDouble accepting a dot as decimal-seperator OR writing doubles with a comma in a file
问:
File myfile = new File("Example.txt"); // the text of myFile looks like this: "3,0"
Scanner scanner1 = new Scanner(myFile);
Double double1 = scanner1.nextDouble(); // reading "3,0" - everything okay
try (Writer filewriter = new FileWriter(myFile)) {
filewriter.write(double1); // writing "3.0" - inconsistent but works for me
filewriter.flush(); // (which obviously will not work for Java)
} catch (IOException e1) {
System.err.println("oops");
}
Scanner scanner2 = new Scanner(myFile);
Double double2 = scanner2.nextDouble(); // There it is: "java.util.InputMismatchException"
我的问题是,如何让它在文件中用分隔逗号写双精度,或者如何让扫描仪读取双精度与分隔点。两者都没问题。
我已经尝试使用 DecimalFormat 等对象,但它没有为我改变任何东西。这就是为什么我会对一些答案感到非常高兴......感谢大家的努力。
答:
1赞
DevilsHnd - 退した
9/8/2020
#1
若要写入文件,请转换要用逗号而不是小数点写入的数据值:
filewriter.write(String.valueOf(double1).replace(".", ","));
读取文件并转换数据值:
// Create a File object to use in Scanner reader.
File myFile = new File("myfile.txt");
// Make sure file exists.
if (!myFile.exists()) {
throw new IllegalArgumentException("The following file path can not be found!" +
System.lineSeparator() + myFile.getAbsolutePath());
}
// Try With Resourses used here to auto-close reader.
try (Scanner scanner2 = new Scanner(myFile)) {
// Read in each numerical token from file...
while (scanner2.hasNext()) {
// Declare a Double variable initialized to null
Double double2 = null;
/* Read in a token and remove any numerical block charaters
for example, 3.456,33 the point is common in European
countries as a thousands separator and the comma as a
decimal point). We also convert the comma decimal separator
to a dot to accomodate your local and the double data type. */
String dblStrg = scanner2.next().replaceAll("[\\.\\s']", "").replaceAll(",", ".");
/* Make sure the numerical String value is
in fact a string representation of an
Integer or a double data type. */
if (dblStrg.matches("-?\\d+(\\.\\d+)?")) {
/* It is so convert the numerical value
to a double data type. */
double2 = Double.parseDouble(dblStrg);
}
/* If however the numerical value read from file
is not a valid Integer or double then inform
User as such. */
if (double2 == null) {
System.out.println("Invalid Double Number! (" + dblStrg + ")");
}
// Display the contents of the double type variable.
else {
System.out.println(double2);
}
}
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
评论
Scanner
filewriter.write(double1.toString())
Double#toString