Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to read String and Double from file [duplicate]

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?

like image 787
Tom Avatar asked Oct 31 '22 04:10

Tom


1 Answers

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.

like image 198
tam Avatar answered Nov 15 '22 05:11

tam