Home » Java » Passing ann array of strings from a file into an array of objects

Passing ann array of strings from a file into an array of objects

Posted by: admin October 29, 2018 Leave a comment

Questions:

I’ll try to keep it concise and only give more code if needed. I’m getting a null pointer exception at line 26 GMIstock[count].setName(values[0]);. The setName() method just sets a string. Originally I had passed the array from another class but I thought that might be the source of my problem and re made the array from inside this class. It passes into values[0 through 2] just fine but trying to pass it from values[0] to the string in Product[count] causes tears. What am I missing here?

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Global_Inventory_Management {

String fileName = "src/data.csv";
File file = new File(fileName);
private Product[] GMIstock;

public void readStock() {

    try {

        Scanner reader = new Scanner(file);
        reader.next();
        int count = 0;
        while(reader.hasNext()) {

            String data = reader.next();
            String[] values = data.split(",");
            System.out.println(values[0]);
            System.out.println(values[1]);
            System.out.println(values[2]);

            //runs fine till right here
            GMIstock[count].setName(values[0]); //sets name of type String in Product
            GMIstock[count].setQuantity(Integer.parseInt(values[1]));
            GMIstock[count].setPrice(Double.parseDouble(values[2]));
            count++;
            System.out.println(GMIstock[count].getName());
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }       
}}
Answers: