2014-02-16 9 views
0

我已將Google搜索了幾天,但沒有多少運氣。我正在嘗試讀取文本文件並使用該信息爲類對象填充數組的專用字段。我是Java的新手,對編程來說很新。如何在Java中使用增變器將文本文件讀取到具有私有字段的數組中

我想到讀入數組看起來非常笨重,我覺得必須有更好的方法,但是我找不到這種特殊情況的好例子。

創建一堆字符串變量是我能夠實現這個功能的唯一方法。也許主力是做這件事的壞地方;也許掃描儀在這裏是一個糟糕的選擇?

有什麼更好的方法來實現這種情況?

包含由空格就行分隔字符串和整數

我的文本文件與此類似:

喬2541 555-1212 1542 345型

鮑勃·8543 555-4488 1982年554型 。 ..等

這裏是我的大多數我的代碼迄今這是內主:

Scanner in = new Scanner(new FileReader("accounts.txt")); //filename to import 
    Accounts [] account = new Accounts [10]; 
    int i = 0; 
    while(in.hasNext()) 
    {   
    account[i] = new Accounts(); 
    String name = in.next(); 
    String acct_num = in.next(); 
    String ph_num = in.next(); 
    String ss_num = in.next(); 
    int open_bal = in.nextInt(); 
    String type = in.next(); 

    account[i].setName(name); 
    account[i].setAcctNum(acct_num); 
    account[i].setPhoneNum(ph_num); 
    account[i].setSSNum(ss_num); 
    account[i].setOpenBal(open_bal); 
    account[i].setType(type); 
    i++; 
    } 

class Accounts 
{ 
    public Accounts() 
    { 
    } 

    public Accounts(String n, String a_num, String ph_num, 
    String s_num, int open_bal, String a_type, double close_bal) 
    { 
    name = n; 
    account_number = a_num; 
    phone_number = ph_num; 
    ssn = s_num; 
    open_balance = open_bal; 
    type = a_type; 
    close_balance = close_bal; 
    } 
    public String getName() 
    { 
    return name; 
    } 
    public void setName(String field) 
    { 
    name = field; 
    } 
    public String getAcctNum() 
    { 
    return account_number; 
    } 
    public void setAcctNum(String field) 
    { 
    account_number = field; 
    } 
    //And so forth for the rest of the mutators and accessors 

    //Private fields    
    private String name; 
    private String account_number; 
    private String phone_number; 
    private String ssn; 
    private int open_balance; 
    private String type; 
    private double close_balance; 
} 

回答

0

我相信你需要分割每一行以獲取每行中包含的數據。您可以使用將返回字符串[]的字符串類的split()。然後,您可以瀏覽字符串數組的每個索引,並將它們傳遞給帳戶類的mutator方法。

也許是這樣的。

while(in.hasNext()) 
{ 
    // will take each line in the file and split at the spaces. 
    String line = in.next(); 
    String[] temp = line.split(" "); 

    account[i].setName(temp[0]); 
    account[i].setAcctNum(temp[1]); 
    account[i].setPhoneNum(temp[2] + "-" + temp[3]); 
    account[i].setSSNum(temp[4]); 
    account[i].setOpenBal((int)temp[5]); 
    account[i].setType(temp[6]); 

    // will account for blank line between accounts. 
    in.next(); 
    i++; 
} 

的電話號碼被分成兩個單獨的指數,所以你必須通過佔前3位的一個指標,最後4,在未來是被重新加入電話號碼。

0
相關問題