Reputation: 77
I am fairly new to Java and have come across an issue which I know should be fairly easy to resolve. However, I cannot figure out where I am going wrong and how I can go about solving this issue. As you can see from my code snippet below I am trying reading from a file using the classical FileReader and I have used a while loop to read the entire file. However, this works all well and good but I would like to multiply the read.nextint() with read.nextdouble() However when I try and multiply them where my Income is it throws an error message. Any solution would be great! Thanks.
FileReader file = new FileReader(fileName);
Scanner read = new Scanner(file);
while (read.hasNext()) {
System.out.print("Room Type: " + read.next());
System.out.print(", Bookings: " + read.nextInt());
System.out.print(", Room Price: " + read.nextDouble());
System.out.println(", Income: " + read.nextDouble() * Double.valueOf(read.nextInt()));
System.out.println(", Tax: " + TaxRate + "\n\n");
}
This is the error message:
Room Type: Single, Bookings: 5, Room Price: 23.5Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
at RoomTaxSystem.Room_Tax_System.main(Room_Tax_System.java:24)
This is the data I am trying to read from the file
Single
5
23.50
Double
3
27.50
Suite
2
50.00
Upvotes: 0
Views: 83
Reputation: 55
The InputMismatchException is thrown because your second read.nextDouble() is trying to interpret the "Double" in your file as a Double Type. If you want to use the first read.nextDouble() value then you have to save it in a variable as Claus said in his answer.
Upvotes: 0
Reputation: 2619
FileReader file = new FileReader(fileName);
Scanner read = new Scanner(file);
while (read.hasNext()) {
System.out.print("Room Type: " + read.next());
int bookings = read.nextInt();
System.out.print(", Bookings: " + bookings);
double price = read.nextDouble();
System.out.print(", Room Price: " + price);
System.out.println(", Income: " + bookings * price);
System.out.println(", Tax: " + TaxRate + "\n\n");
}
Upvotes: 2