2016-03-31 9 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);