Reputation: 1086
I want to read a file which has the following form:
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
And with this code:
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();
I get an Input Mismatch Exception in the middle of reading the second line of data. Any ideas why is that?
EDIT: If I output every variable after having read it, the output is:
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)
Upvotes: 1
Views: 420
Reputation: 14217
Your regex should be:
in.useDelimiter(";|\\s+");
because your data has \r
in Windows with new line \n
in the end of line, In the second loop, the delimiter will include \r
character as an element:
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();
}
The output:
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)
the exception is actual throwed by the second loop to parse double.
we can see the second customerID
is empty.
and for the second loop the Price value is: milk
, so it will throw
InputMismatchException
for Double parse
Upvotes: 2
Reputation: 5423
Alternatively just read the whole line then use split:
String nextLine=in.nextLine();
String[] splitted= nextLine.split(";|\\s");
Upvotes: 2