我已將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;
}