2017-01-16 63 views
1

嗨,大家好,我是Java的初學者,我試圖從文件中讀取一些數據,但是,當它試圖讀取雙重的價值,我發生了錯誤無法弄清楚爲什麼。這是我的代碼:讀雙使用掃描文件,java.util.InputMismatchException

package bestcombo; 
import java.io.*; 
import java.util.Scanner; 
public class Componentes 
{ 
    String name = ""; 
    Lojas[] stores = new Lojas[8]; 
    public void ComponenteNome(String nome) 
    { 
     name = nome; 
    } 
    public void InicializeStores() 
    { 
     for (int i = 0; i < 8; i++) 
     { 
      stores[i] = new Lojas(); 
     } 
    } 
    public void InserirInformacao() throws IOException 
    { 
     int i = 0, val = 0, quant = 0; 
     double price = 0; 
     String FileName = ""; 
     Scanner ReadKeyboard = new Scanner(System.in), ReadFile = null; 
     InicializeStores(); 
     System.out.println("File:\n"); 
     FileName = ReadKeyboard.nextLine(); 
     ReadFile = new Scanner(new File(FileName)); 
     while(ReadFile.hasNext()) 
     { 
      ReadFile.useDelimiter(":"); 
      val = ReadFile.nextInt(); 
      ReadFile.useDelimiter(":"); 
      price = ReadFile.nextDouble(); 
      ReadFile.useDelimiter("\\n"); 
      quant = ReadFile.nextInt(); 
      stores[i].LojaValor(val); 
      stores[i].LojaQuantidade(quant); 
      stores[i].LojaPreco(price); 
     } 
    } 
} 

這是我的文件中的數據:

1:206.90:1 
2:209.90:1 
3:212.90:1 
4:212.90:1 
5:213.90:1 
6:224.90:1 
7:229.24:1 
8:219.00:1 

這是錯誤

Exception in thread "main" java.util.InputMismatchException 
at java.util.Scanner.throwFor(Scanner.java:864) 
at java.util.Scanner.next(Scanner.java:1485) 
at java.util.Scanner.nextDouble(Scanner.java:2413) 
at bestcombo.Componentes.InserirInformacao(Componentes.java:34) 
at bestcombo.BestCombo.main(BestCombo.java:13) 

回答

0

從文件我想讀書當推薦使用getNextLine(),它使得代碼更簡單並提取值。另外,您讀取的數據文件是冒號分隔的,這使得提取值非常容易。嘗試使用此while循環代替

while(ReadFile.hasNextLine()) 
{ 
    String inputOfFile = ReadFile.nextLine(); 
    String[] info = inputOfFile.split(":"); 
    try{ 
     if(info.length == 3) 
     { 
      val = Integer.parseInt(info[0]); 
      price = Double.parseDouble(info[1]); 
      quant = Integer.parseInt(info[2]); 
      stores[i].LojaValor(val); 
      stores[i].LojaQuantidade(quant); 
      stores[i].LojaPreco(price); 
      i++; 
     } 
     else 
     { 
      System.err.println("Input incorrectly formatted: " + inputOfFile); 
     } 
    }catch (NumberFormatException e) { 
     System.err.println("Error when trying to parse: " + inputOfFile); 
    } 
} 

我的猜測是有一個額外的新行字符或您正在閱讀的文件內的東西。上面應該能夠很容易地處理你的文件。此實現的另一個優點是,即使遇到數據格式不正確的文件中的位置,它也會繼續從文件讀取數據。

+0

謝謝你,我會試試! –

+0

讓我知道它是否工作@TiagoLima –

+0

它工作完美,只有一件事是缺少哪一行是「i ++;」。萬分感謝! :) –