Tom Tom - 7 months ago 11
Java Question

Need to read String and Double from file

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?

Answer

You could try this way:

while(reader.hasNextLine()){
    String[] values = reader.nextLine().split("\\s+");
    name= values[0];
    salary = Double.valueOf(values[1]);
    System.out.println(name + " " + salary + "\r\n");
}