I'm having some trouble trying to read a String and a Double from a txt file. Here is my txt file:
Mike 300.50
John 260
Lisa 425.33
And here is the code I am using to read them:
reader = new Scanner();
while(reader.hasNext()){
name= reader.next();
salary = reader.nextDouble();
System.out.println(name + " " + salary + "\r\n");
}
Whenever I run this code, Exception in thread "main" java.util.InputMismatchException
appears telling me the problem is in nextDouble()
.
Does anybody know how to solve this?
reader = new Scanner();
while(reader.hasNext()){
name= reader.next();
salary = reader.nextDouble();
System.out.println(name + " " + salary + "\r\n");
reader.nextLine();
}
Try this. What's happening is that the scanner is reading the empty line after every double, so name will be the empty line, and it will read (for example) John as the salary, and give you that exception.
So what I did was add that little line of code: reader.nextLine();
so it could skip that empty line. Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With