Reputation: 229
I'm having problems reading in my file into an array of objects. I created an if statement so that the lines of data get separated into two different subgroups one is produce and the other is cleaning. But when I run the program the objects that are created are empty. How do I connect the file into the objects? I'm missing something crucial.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Inventory{
public static void main(String[] args){
int i=0;
Product[] pr=new Product[16];
File InventoryFile=new File("inventory.csv");
Scanner in=null;
try{
in=new Scanner(InventoryFile);
while(in.hasNext()){
String line=in.nextLine();
String[]fields=line.split(",");
if(fields[0].equals("produce"))
pr[i]= new Produce();
else
pr[i]=new Cleaning();
i++;
}
System.out.println(pr[6]);
}catch(FileNotFoundException e){
System.out.println("Arrgggg"+e.getMessage());
}
}
}
Upvotes: 5
Views: 1648
Reputation: 107
Your problem stems from not even setting your varibles in your objects all you haven been doing is making them produce and cleaning but not filled in their fields.
I can not answer further without knowing how you set up your produce, product, and cleaning classes and how they get their varibles filled.
Upvotes: 3
Reputation: 124
When you're adding your Produce/Cleaning objects in your while loop here
if(fields[0].equals("produce"))
pr[i]= new Produce();
else
pr[i]=new Cleaning();
you're just adding new, blank Produce/Cleaning objects into your array.
To fix this, you need to have some getters and setters in your Produce/Cleaning objects classes, so that you can set the values of whatever variables it is you're trying to set (Strings for names of produce/cleaning items? doubles for prices? ints for # in-stock?).
Once you have that, you can give your Produce/Cleaning objects values that will mean something when you try to pull them up again, i.e.
if(fields[0].equals("produce"))
pr[i]= new Produce(fields[1], fields[2], fields[3]); //assuming you make a constructor that takes these values
else
pr[i]=new Cleaning(fields[1], fields[2], fields[3]);
.
.
.
if(pr[i] instanceOf Produce)
String vegName = pr[i].getName();
int stock = pr[i].getStock();
double price = pr[i].getPrice();
I'd need to know more about what is in the csv and what you're trying to create with enter code hereyour array to give you more help, but hopefully this is a start.
Upvotes: 0
Reputation: 1642
You are not filling your Objects, you are creating, but not filling them. You can create a constructor like this:
public Product(String a, int b, int c, String, d, int e)
{
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
and in the extended classes you just call the super constructor.
public Produce(String a, int b, int c, String, d, int e)
{
super(a,b,c,d,e);
}
and when you create them call:
new Produce(fields[0],Integer.parseInt(fields[1]),Integer.parseInt(fields[2]),fields[3],Integer.parseInt(fields[4]));
Upvotes: 0