2016-03-31 11 views
2

来读取它我必须在文件中编写一个双精度数并稍后读取该文件和Double,但我有一个ImputMismatchException。我已经调试了代码,问题在于我用来写文件的PrintWritter,将数字写成一个点,如下所示:12.3。而且我用来读取数Scanner.nextDouble()返回ImputMismatchException如果开关输入心不是这样的:12,3写一个双精度值用于稍后用Scanner.nextDouble()

这里是我的代码软件写:

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并正确读取数?

这是我的第一篇文章,也许我犯了一些与我的语法错误,因为我是西班牙语,我不会说英语很好。

谢谢你的时间。

回答

2

尝试初始化Scanner使用适当的位置,这样的点和逗号的处理是正确的,就像这样:

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

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

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