使用scanner,java.util.InputMismatchException从文件读取double

时间:2017-01-16 17:31:33

标签: java double java.util.scanner

大家好,我是Java的初学者,我试图从文件中读取一些数据,但是当它试图读取double的值时发生了错误,我无法弄清楚原因。这是我的代码:

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)

1 个答案:

答案 0 :(得分:0)

从文件中读取时,我建议使用getNextLine(),它可以实现更简单的代码和值的提取。另外,您读入的数据文件是冒号分隔的,这使得提取值非常容易。尝试使用while 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);
    }
}

我的猜测是你正在阅读的文件中有一个额外的新行字符或其他内容。以上应该可以很容易地处理您的文件。此实现的另一个优点是,即使您遇到数据格式不正确的文件中的位置,它也将继续从文件中读取。