如何在Java中使用mutators将文本文件读入带有私有字段的数组

如何在Java中使用mutators将文本文件读入带有私有字段的数组,java,arrays,mutators,Java,Arrays,Mutators,我已经在谷歌上搜索了几天,运气不太好。我试图读取一个文本文件,并使用该信息填充类对象数组的私有字段。我是Java新手,一般来说对编程非常陌生 我想到的读取数组的方法似乎非常笨拙,我觉得一定有更好的方法,但我找不到一个适合这种特殊情况的好例子 创建一组字符串变量是我实现这一功能的唯一方法。也许main是一个不适合这样做的地方;也许扫描器在这里是个糟糕的选择 有什么更好的方法来实施这种情况 我的文本文件包含由行上的空格分隔的字符串和整数,类似于以下内容: 乔2541555-1212345 1542型

我已经在谷歌上搜索了几天,运气不太好。我试图读取一个文本文件,并使用该信息填充类对象数组的私有字段。我是Java新手,一般来说对编程非常陌生

我想到的读取数组的方法似乎非常笨拙,我觉得一定有更好的方法,但我找不到一个适合这种特殊情况的好例子

创建一组字符串变量是我实现这一功能的唯一方法。也许main是一个不适合这样做的地方;也许扫描器在这里是个糟糕的选择

有什么更好的方法来实施这种情况

我的文本文件包含由行上的空格分隔的字符串和整数,类似于以下内容:

乔2541555-1212345 1542型

鲍勃8543 555-4488 554 1982型 ... 等等

以下是我到目前为止的主要代码:

   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;
} 

我相信您需要拆分每一行,以便获得每一行中包含的数据。您可以使用string类的split(),它将返回字符串[]。然后可以遍历字符串数组的每个索引,并将它们传递给account类的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位在下一个索引中。

  • 科目[]
    替换为
    集合
  • 在这种特殊情况下,使用
    扫描仪
    似乎是合理的,但请看一下处理文本的其他方法(性能与便利性):
  • 使用变量或构造函数设置帐户参数可能不是最佳选择: