Search code examples
javajava.util.scannerinputmismatchexception

Input mismatch when reading from a file


I have a file with data organized like so:

Hyundai Santa Fe

2005 16999 8

Mercury Mountaineer AWD

2004 17999 7.5

Mercury Grand Marquis

2006 19999 12.5

The first line being car name, next line being year, price, and discount amount. I'm trying to read a file with many of these lines and the kicker is that price and discount isn't always represented as a double.

Here is a snippet of code which I wrote but does not properly parse through the lines. I get an input mismatch exception.

What am I doing wrong?

try {

         Scanner scanFile = new Scanner(file);
         while(scanFile.hasNext()) {   

            String carName = scanFile.nextLine();

            int year = scanFile.nextInt();
            double listPrice = scanFile.nextDouble();
            double percentDiscount = scanFile.nextDouble();

            double discountAmount = calculateDiscount(listPrice, percentDiscount);
            double netPrice = calculateNetPrice(listPrice, discountAmount);

            carList.add(new Proj1CarData(carName, year, listPrice, percentDiscount, discountAmount, netPrice));

         }
      } catch(FileNotFoundException fnfe) {
            System.out.println("Unable to locate the file supplied.");
      }

Solution

  • nextLine() is defined as

    Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line. Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.

    meaning that nextLine() will read from the current position to line separator.

    After a first call to double percentDiscount = scanFile.nextDouble();, the Scanner's cursor is at after 8 in line 2005 16999 8.

    On the second iteration of the loop, String carName = scanFile.nextLine(); will read an empty string as there is no string between 8 and the line separator. Then, int year = scanFile.nextInt(); throws an InputMismatchException as the cursor now is looking at the Mercury Mountaineer AWD.

    I don't know if I was able to explain myself well.

    To resolve this problem, simplified version would be just to add extra nextLine() call at the end of the loop:

    
    String carName = scanFile.nextLine();
    
    int year = scanFile.nextInt();
    double listPrice = scanFile.nextDouble();
    double percentDiscount = scanFile.nextDouble();
    scanFile.nextLine();
    

    I suppose the better way of handling this is to read each line using nextLine() and check if the line is carname or year/price/discount info or not.

    Hope this helped.