Search code examples
javacsvbufferedreader

Java parsing csv and creating objects


I am getting a "non-static method cannot be referenced from a static context" - which I believe basically means that the object is not getting created. What am I doing wrong?

public void loadData() {
    String csvFile = "/data/patientList.csv";
    BufferedReader br = null;

    try {

        br = new BufferedReader(new FileReader(csvFile));
        br.readLine();
        String line1 = null;
        while ((line1 = br.readLine()) != null) {
            String[] patient = line1.split(",");
            int bedNum = Integer.parseInt(patient[0]);
            Patient patient1 = new Patient(bedNum, patient[1], patient[2], patient[3], patient[4],
                    RESPIRATORY_RATE, HEART_RATE, SYSTOLIC, SPO2);

throws errors here, for example:

patientNameField.setText(Patient.getFistName());

Solution

  • This error sounds like your trying this:

    public static void main(String args[]) {
        loadData();
    }
    
    public void loadData() { /* method code */ }
    

    This doesn't work, because the method loadData is not static and needs an object to be called on.

    Change your code as follows:

    public class MyClass { // you can name your class like you want
        public static void main(String args[]) {
            final MyClass instance = new MyClass(); //assuming there is a non-argument constructor
            instance.loadData(); // call "loadData" on a specifc instance of MyClass
        }
    
        public void loadData() { /* method code */ }
    }