2017-01-16 45 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 ++;”。万分感谢! :) –