Java:更改scanner.nextDouble接受点作为小数点分隔符或在文件中用逗号写入双精度数

问题描述

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等对象,但是对我来说并没有任何改变。这就是为什么我会对某些答案感到非常高兴的原因……谢谢大家的尝试。

解决方法

要写入文件,请用逗号而不是小数点转换要写入的数据值:

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);
}
,

您可以执行以下操作:

// Define the formatter
DecimalFormat formatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.GERMAN);
formatter.applyPattern("#,#0.0");

try (Writer filewriter = new FileWriter(myFile)) {
    filewriter.write(formatter.format(double1))
    //...
} catch (IOException e1) {
    //..
}