0

I just started using Java recently so please bear with me. I'm trying to create an array of the object Product by reading data from a csv file with the format

Name,Price,Stock

but every time I'm trying using the Load() function it keeps giving me an error in the Product constructor line.

  private Product[] product = new Product[100];

  public Product[] Load() throws FileNotFoundException {
    int  counter = 0;
    boolean end = false;

    Scanner scanner = new Scanner(new File("products.csv"));
    scanner.useDelimiter(",");

    while (!end) {
        if (scanner.hasNext()) {
            product[counter] = new Product(scanner.next(), scanner.nextFloat(), scanner.nextInt());
            counter++;
        }
        else {
            end = true;
        }

    }

    scanner.close();
    return product;
}

the error message is java.util.scanner.next(unknown source), and the same error for both scanner.nextFloat() and scanner.nextInt()

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 ScoutShop.CSVReader.Load(CSVReader.java:20)
at ScoutShop.Main.main(Main.java:11)
mzanaty
  • 1
  • 2

2 Answers2

0

The generated java class should also be the same location of products.csv.

Or try to put the products.csv in the root or in `C:\products.csv and do (and see what happens):

 Scanner scanner = new Scanner(new File("C:\\products.csv"));
pvma
  • 235
  • 4
  • 11
0

Check the Java Docs for the new File(String path) knowing that you must specify the exact file path for the file you are trying to read

check this answer for CSV parsing CSV Parsing errors by Scheintod

private Product[] product = new Product[100];
public Product[] load() throws FileNotFoundException {
    int  counter = 0;
    Scanner scanner = new Scanner(new File("products.csv"));
    scanner.useDelimiter(",");
    // try the following while loop without use of if-else statements to 
    // avoid complexity in case of up scaling/maintaining your application 
    while(scanner.hasNext()){
         // System.out.print(scanner.next()+"|");
         product[counter] = new Product(scanner.next(), scanner.nextFloat(), 
         scanner.nextInt());
         counter++;
    }
    scanner.close();
    return product;
}
El Sheikh
  • 203
  • 4
  • 24