0

So I already read the documentation and a bunch of tutorials on it but it's still not clicking in my head how to fix the "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1" error in my code since I can't for the life of me see anything wrong with it.

 public  HashMap<String, product> getAllProducts() {
            HashMap<String, product> productMap = new HashMap<String, product>();

            //create a file object from the external file
            File productFile = new File("src/main/resources/stock.sample.csv");

            // Catch Exception when reading the file using try-catch block
            try {
                // Read an external file: stock.sample.csv via Scanner
                Scanner scanner = new Scanner(productFile);
                while (scanner.hasNext()){
                    String fileRecord = scanner.nextLine();

                    String[] fileRecordSplit = fileRecord.split(",");

                    product product = new product();
                    product.setId(fileRecordSplit[0]);
                    product.setName(fileRecordSplit[1]); // Throws the java.lang.ArrayIndexOutOfBoundsException:
                    // Index 1 out of bounds for length 1
                    product.setCategory(fileRecordSplit[2]);

                    Price price = new Price();
                    price.setAmount(Double.parseDouble(fileRecordSplit[3]));

                    product.setPrice(price);
                           productMap.put(product.getId(), product);
                }

            } catch (FileNotFoundException e){
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return productMap;
        }
    }
CrazyCoder
  • 350,772
  • 137
  • 894
  • 800
  • Can you print out the line from the file that causes this exception? – Mureinik Mar 03 '20 at 19:49
  • The problem you’re facing is caused, because the array is of just one element and you’re trying to read the second element! Please keep in mind this: the first position of the array is 0, the second one at 1! I suggest you to use StringTokenizer class! – I love coding Mar 03 '20 at 19:49
  • @Mureinik do you mean the output? It's like this : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1 at csc1035.project3.controller.ProductManager.getAllProducts(ProductManager.java:27) at csc1035.project3.pos.main(pos.java:15) – Eris Morrigan Mar 09 '20 at 14:23

0 Answers0