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.