写一个 Double 数字,稍后用 Scanner.nextDouble() 读取它

Writing a Double number for read it later with Scanner.nextDouble()

我必须在文件中写入一个 Double 数字,然后读取该文件和那个 Double,但我有一个 ImputMismatchException。我已经调试了代码,问题是我用来编写文件的 PrintWritter 写入了一个点号,如下所示: 12.3 。如果输入不是这样,我用来读取该数字 returns 的 Scanner.nextDouble() InputMismatchException:12,3

这是我要编写的代码:

public void crearVentaNueva(int codigo, double precio, String nombre) throws IOException {
    FileWriter fw = new FileWriter(archivoVentas, true);
    PrintWriter pw = new PrintWriter(fw);

    pw.println(codigo + " dato " + nombre + " dato " + precio + " dato ");

    pw.close();
    fw.close();

    nVentas++;
    ventas.add(new Venta(codigo, precio, nombre));
}

这是我的阅读代码:

private void leerArchivoVentas() throws IOException {

    int codigo;
    double precio;
    String nombre;

    try {

        FileReader fr = new FileReader(archivoVentas);
        Scanner lector = new Scanner(fr);
        nVentas = 0;
        while (lector.hasNextLine()) {
            nVentas++;
            lector.nextLine();
        }
        lector.close();
        fr.close();

        ventas = new ArrayList<Venta>();

        fr = new FileReader(archivoVentas);
        lector = new Scanner(fr);
        lector.useDelimiter("\s*dato\s*");

        for (int i=0; i<nVentas; i++) {

            codigo = lector.nextInt();
            nombre = lector.next();
            precio = lector.nextDouble();

            ventas.add(new Venta(codigo, precio, nombre));

        }

        lector.close();
        fr.close();

    }
    catch(Exception e) {

        FileWriter fw = new FileWriter(archivoVentas);

        ventas = new ArrayList<Venta>();
        nVentas = 0;

        fw.close();
    }
}

如果没有 ImputMismatchException 并正确读取数字,我该怎么办?

尝试使用适当的语言环境初始化 Scanner,以便正确处理点和逗号,如下所示:

FileReader fr = new FileReader(archivoVentas);
Scanner scanner = new Scanner(fr).useLocale(Locale.US);

您可以使用重载的 String.format 方法并指定适当的语言环境,如:

String.format(Locale.FRANCE, "%.2f", someDouble);