0

This is my method to read data in files into array:

public ArrayList<Product> readProductsFromFile()
    {
        ArrayList<Product> products = new ArrayList<>();
        
        File products_list = new File("/Users/User/Desktop/utar/ooad/Product.txt");
        Scanner products_reader;
        try 
        {
            products_reader = new Scanner(products_list);
            
            while(products_reader.hasNextLine())
            {
                String id = products_reader.nextLine();
                String name = products_reader.nextLine();
                String date = products_reader.nextLine();
                double price = products_reader.nextDouble();
                int quantity = products_reader.nextInt();
                String brand = products_reader.nextLine();
                
                products.add(new Product(id, name, date, price, quantity, brand));
            }
            
            products_reader.close();
        } 
        
        catch (FileNotFoundException e) 
        {
            System.out.println("Error : Product file is not found.");
            System.out.println();
        }
        
        return products;
    }

This is my text file that this method read data from:

MMM001
Rice
11/11/2022
1.0
100
SUNRISE
MMM002
Sugar
11/11/2022
1.0
100
SUGARKING
MMM003
Salt
01/02/2022
2.0
4
SALTKING

when i run, the system show

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Admin.readProductsFromFile(Admin.java:162)
    at Main.main(Main.java:16)

When i change to nextLine() to next(), it works fine. How can i modify my code to use nextLine() with no error.

Tobias S.
  • 21,159
  • 4
  • 27
  • 45
Nino
  • 11
  • 3
  • Maybe you are missing a trailing newline in your file? – CherryDT Apr 12 '22 at 16:56
  • 1
    After you read a token like `nextDouble` or `nextInt`, you need an extra `readLine` to consume the rest of that line. The same cause as [Scanner is skipping nextLine() after using next() or nextFoo()](https://stackoverflow.com/q/13102045/3890632). – khelwood Apr 12 '22 at 17:01

0 Answers0