-1

I'm trying to read a .adi file that has a line format of String, Int and Double.

For example:

 Ford,Fusion,2010,85254,12855.58

For the code, I'm required to use a try-catch statement and the method header has to throw the exception. Furthermore, I have a while statement inside the try block to process the data, however I keep getting the InputMismatchException thrown.

So it looks like:

        try{
            Scanner scan = new Scanner(inventoryFile)
            scan.useDelimiter(FIELD_SEPARATOR);
            while(scan.hasNext()) {
                
                String make = scan.next();
                String model = scan.next();
                int year = scan.nextInt();
                int mileage = scan.nextInt();
                double price = scan.nextDouble();
                Automobile auto = new Automobile(make, model, year, mileage, price);
                fileInventory.add(auto);
            }

May I know how to resolve this issue? Thanks in advance.
TechGeek49
  • 476
  • 1
  • 7
  • 24
  • _"I keep getting an InputMismatchException"_ -- Please [edit] your post and add the complete stack trace (format as code) and indicate the statement that throws the exception. Please read [ask] to learn how to write questions on StackOverflow. – Jim Garrison Jan 31 '21 at 23:28

1 Answers1

2

You didn't specify, but I presume FIELD_SEPARATOR is set to ",". So rather than the default (whitespace) it is expecting ONLY single commas to delimit fields.

The first line ends with a newline character, which does not terminate the last field, so it's waiting until it reads the next line and attempts to scan the value from the first line concatenated with \n and the name from the second line.

So, for instance, for this input

-Ford,Fusion,2010,85254,12855.58
-Chevy,Silverado,2015,66454,17333.00

what your code actually sees is

-Ford,Fusion,2010,85254,12855.58\n-Chevy,Silverado,2015,66454,17333.00

and it's splitting on commas only, so the price field contains 12855.58\n-Chevy, which is clearly not a valid number.

I personally hate that Scanner was included in Java, it is the cause of an incredible amount of grief for beginners and is responsible for many, many questions here.

The simple fix in your case is to add one line

double price = scan.nextDouble();
scan.nextLine();  // ADD THIS LINE

to skip to the start of the next line.

Jim Garrison
  • 85,615
  • 20
  • 155
  • 190