how to use a while loop to read from text file

Viewed 880

I need to be able to read 3 separate blocks of text from a file and display them including the calculations to the console using a while loop. At the moment I can only get one block of text to display.

I couldn't figure out how to format it on here exactly like it is in the text file so excuse the image. Text File:

public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub
    FileReader input = new FileReader ("rooms.txt");
    Scanner console = new Scanner(System.in);
    Scanner read = new Scanner (input);
    final double defaultTax = .20;
    
    
    System.out.println("Do you wish to specify a custom tax rate? (yes/no): ");
    
     if (console.next().equals("yes")) {
         System.out.println("What would you like the tax rate to be?");
     }      
    //use while loop
     
    else
     {

        while (read.hasNextLine()) {
        
        String roomType = read.nextLine();
        int rooms = read.nextInt();
        double price = read.nextDouble();
        double totalIncome = (double) (rooms*price);
        double tax = (double) (price*rooms*defaultTax);
    System.out.println("Room type: " + roomType + " | No. of rooms: " + rooms + " | Room price: " + price + " | income: " + totalIncome + " | tax: " + tax);
        }
     }
}

CURRENT OUTPUT: Room type: Single | No. of rooms: 5 | Room price: 23.5 | income: 117.5 | tax: 23.5

The desired output would include all of the data, including the calculations.

Current error message:
    Exception 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.nextInt(Scanner.java:2258)
    at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
    at cwk/cwk.test1.main(test1.java:31)

I am literally just a uni student looking for a bit of help on a bit of one module. I'm not a programmer, I'm not doing a programming course. please don't delete my question.

1 Answers

The issue is related to whitespace. When you call nextLine it will read a whole line, until it encounters \n or the end of the file. When you call nextInt and nextDouble it will skip any preceding whitespace, however it will not consume any whitespace after.

So the first iteration of your while loop is working fine. However the next iteration when nextLine is called, then an empty string is returned. After that when nextInt is called, then it encounters "Double" and thus you get an InputMismatchException.

The easiest way to fix this, is that at the end of your while loop, you can skip all subsequent whitespace:

while (read.hasNextLine()) {
    // Keep everything you already have

    read.skip("\\s+");
}
Related