Java Scanner - 两个分隔符和异常

时间:2015-10-27 09:44:49

标签: java java.util.scanner delimiter

我想阅读一个具有以下形式的文件:

c00004;Doe John;bananas;4.0;50.0
c00003;Doe John;milk;4.0;5.0
c00001;Doe John;milk;4.0;10.0
c00001;Doe John;milk;5.0;2.0

使用此代码:

Scanner in = new Scanner(Paths.get(fileName));
in.useDelimiter(";|\\s");

while(in.hasNext())
{
    String customerID = in.next();
    String surname = in.next();
    String firstName = in.next();
    String productName = in.next();
    double price = in.nextDouble();
    double quantity = in.nextDouble();

    Purchase newPurchase = new Purchase(customerID, surname, firstName, productName, price, quantity);
}

in.close();

我在读取第二行数据时遇到输入不匹配异常。任何想法为什么会这样?

编辑: 如果我在读完后输出每个变量,输出为:

c00004 Doe John bananas 4.0 50.0 
 c00003 Doe John 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 CustomersPurchaseSortFind.readFile(CustomersPurchaseSortFind.java:31)
    at Main.main(Main.java:9)

2 个答案:

答案 0 :(得分:2)

或者只读完整行然后使用split:

String nextLine=in.nextLine();
String[] splitted= nextLine.split(";|\\s");

答案 1 :(得分:2)

你的正则表达式应该是:

in.useDelimiter(";|\\s+");

因为您的数据在 Windows 中有\r,在行尾有新行\n,在第二个循环中,分隔符将包含\r个字符作为一个要素:

    int i = 1;
    while(in.hasNext())
    {
        System.out.println("line: " + i++);
        String customerID = in.next();
        String surname = in.next();
        String firstName = in.next();
        String productName = in.next();
        double price = in.nextDouble();
        System.out.println("Price: " + price);
        double quantity = in.nextDouble();
    }

输出:

line: 1
customerID: c00004
Price: 4.0
line: 2
customerID: 
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:909)
    at java.util.Scanner.next(Scanner.java:1530)
    at java.util.Scanner.nextDouble(Scanner.java:2456)
    at Test.main(Test.java:32)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

异常是由第二个循环实际抛出来解析double。

我们可以看到第二个customerID为空。

对于第二个循环,价格值为:milk,因此throw

InputMismatchException Double parse