写入一个Double数字以便稍后使用Scanner.nextDouble()读取



我必须在文件中写入一个Double数字,然后读取该文件和该Double,但我有一个ImputMismatchException。我已经调试了代码,问题是我用来写文件的PrintWritter用一个点写数字,就像这样:12.3。如果输入不是这样,我用来读取该数字的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);

最新更新