我在将文件读入一个对象数组时遇到了问题.我创建了一个if语句,以便将数据行分成两个不同的子组,一个是生成的,另一个是清理的.但是当我运行程序时,创建的对象是空的.如何将文件连接到对象?我错过了一些关键的东西.
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
你不是在填充你的对象,你是在创建,但不是填充它们。您可以像这样创建一个构造函数:
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;
}
Run Code Online (Sandbox Code Playgroud)
在扩展类中,您只需调用超级构造函数。
public Produce(String a, int b, int c, String, d, int e)
{
super(a,b,c,d,e);
}
Run Code Online (Sandbox Code Playgroud)
当你创建它们时调用:
new Produce(fields[0],Integer.parseInt(fields[1]),Integer.parseInt(fields[2]),fields[3],Integer.parseInt(fields[4]));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1476 次 |
| 最近记录: |