2012-02-01 121 views
2

我想使用一个文本文件并将每行放入一个classobject数组中。这是我的代码将字符串文本文件转换为对象数组

try { 
    // Open the file that is the first 
    // command line parameter 
    FileInputStream fstream = new FileInputStream("Patient.txt"); 
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream)); 
    String strLine; 
    // Read file line by line 
    while ((strLine = br.readLine()) != null) { 
     // Print the content on the console 
     System.out.println (strLine); 
    } 
    // Close the input stream 
    in.close(); 
} catch (Exception e) { // Catch exception if any 
    System.err.println("Error: " + e.getMessage()); 
} 

我需要转换成一个数组对象这一点,这是我希望它看起来像

Patient1 p[] = new Patient1[5]; 
p[0] = 001, "John", 17, 100, 65, 110, 110, 110, 109, 111, 114, 113, "Swaying, Nausea"; 
p[1] = 002, "Sun Min", 18, 101, 70, 113, 113, 110, 119, 111, 114, 113, "None"; 

等。

+1

我想要一只小马。尽管如此,你需要告诉我们你尝试过什么,然后提出具体的问题。 – 2012-02-01 03:45:41

回答

0

您必须创建带有13个字段,构造函数和setter/getter的Patient类。

public class Patient 
{ 
    private String field1; 
    private String field2; 
    private int field3; 
    .... 
    public void setField1(String field1) { this.field1=field1; } 
    public String getField1() { return field1;} 
    ... 
} 

并使用ArrayList<Patient>代替阵列。

ArrayList<Patient> patients=new ArrayList<Patient>(); 
Patient pat=new Patient(); 
//set value to the patient object 
patients.add(pat); 
+0

我有13个方法,如getID()和getName()如何连接字符串与正确的方法? – user1181810 2012-02-01 04:12:20

1

大厦掉什么AVD曾建议,你可以完成你想要的是把你的价值观构造是什么 - 尽管这不是建议在构造函数(为便于阅读和调试的缘故)用过多的参数。根据您的数据排序和阅读方式,您甚至可以使用String.split将所有内容整合到一种类型中(即字符串)。

public class Patient { 

    public Patient(String name, String id, String symptoms, String measurements) { to get the individual fields from using a delimiter. 

     // Stuff to fill in the fields goes here 
    } 
} 

你可以使用调用new Patient("John, "001", "Swaying, Nausea", ...)来调用它。这又取决于你如何阅读进入的数据;如果您无法以合理的方式将数据集中起来,那么您也可以选择创建accessors and mutators

+0

public Patient1(int i,String n,int a,double w,int h,int bp1,int bp2,int bp3,int bp4,int bp5,int bp6,int bp7,String s){ id = i ;
name = n;
age = a;
weight = w;
height = h;
BP1 = bp1;
BP2 = bp2;
BP3 = bp3;
BP4 = bp4;
BP5 = bp5;
BP6 = bp6;
BP7 = bp7;
SYM = s;
现在我该怎么办? – user1181810 2012-02-01 04:10:42

+0

我可以用阵列号识别每一行吗? – user1181810 2012-02-01 04:32:32

+0

@ user1181810,你可以编辑你的问题,包括你到目前为止所尝试的;它会更容易阅读。至于用数组来识别每一行,恐怕我不明白你的意思。如果将每个Patient对象存储到一个数组或ArrayList中,则可以按照它们的顺序返回它们(您可以扩展'toString()'并返回每个对象的值if如果您仍然不确定,请更新您的问题以阐明您的意图。 – Makoto 2012-02-01 05:00:34