I really hope that someone can provide some suggestions or help to guide me in the right direction.
I am trying to use a scanner to parse a string and use its elements with methods. It is formatted as so:
String line = "Mercedes, 124 124.11, 45";
When I parse the string, I get a java.util.InputMismatchException
here is a snippet:
Scanner line = new Scanner(line);
line.useDelimiter(",");
while(line.hasNext())
{
String car = line.next();
int id = line.nextInt();
double serial = line.nextDouble();
int code = line.nextInt();
}
Any suggestions will be a hugely appreciated.
Hi
In the example above you have named your scanner as line and your string as line. Thats is confusing and makes it difficult for you to search for faults. In the string there is no "," after the id number. Maybe you just missed it writing it down in your post here? If you also missed it in your code you will get an error.
I could be that your .useDelimiter(",*"); works better if you tell it there is a space after the "," like this .useDelimiter(",\\s*");
You probably will get some error trying to catch the serial like this:
double serial = line.nextDouble();
Try like this instead:
String s = new String();
double serial = Double.valueOf(s = line.next());
This way you catch the serial as a string and makes a double out of the value from the string.
I am not really sure of why you have put in inside a while loop but my advise is to take it out of the loop if you have trouble until you catch does results you want and first then put your stuff inside any kind of loop.
Use System.out.println(); to test what you get and how it looks.
I can not see that you are closing your scanner?
You do that in the same way you are closing streams, whit a simple .close();
Hope this will give you some help.
Good luck =)