1

我有一个文本文件,我试图用字符串标记器分解。这是文本文件的几行:

Mary Smith 1 
James Johnson 2 
Patricia Williams 3 

我正在尝试分解为名字、姓氏和客户 ID。

到目前为止,我已经能够做到这一点,但在玛丽史密斯之后就停止了。

这是我的代码:

  public static void createCustomerList(BufferedReader infileCust,
            CustomerList customerList) throws IOException
{    


            String  firstName;
            String  lastName;
            int  custId;


            //take first line of strings before breaking them up to first last and cust ID
            String StringToBreak = infileCust.readLine();
            //split up the string with string tokenizer
            StringTokenizer st = new StringTokenizer(StringToBreak);

            firstName = st.nextToken();

            while(st.hasMoreElements())
            {
            lastName =  st.nextToken();
            custId = Integer.parseInt(st.nextToken());
            CustomerElement CustomerObject = new CustomerElement();
            CustomerObject.setCustInfo(firstName,lastName,custId);
            customerList.addToList(CustomerObject);

            }


    }
4

3 回答 3

3
String StringToBreak = infileCust.readLine();

从文件中读取第一行。然后你用它喂给 StringTokenizer。StringTokenized 找不到更多令牌是正常的。

您必须创建一个包含所有这些内容的第二个循环来读取每一行。这是:

outer loop: readLine until it gets null {
   create a StringTokenizer that consumes *current* line
   inner loop: nextToken until !hasMoreElements()
}

好吧,确实你不需要做一个内部循环,因为你有三个不同的字段。足够了:

name = st.nextToken();
lastName = st.nextToken();
id = st.nextToken;
于 2012-02-13T16:56:50.647 回答
1

对于外循环,您需要将当前行的内容存储在 stringToBreak 变量中,以便您可以在循环内访问它。每行都需要一个新的 StringTokenizer,因此它需要在循环内。

String stringToBreak = null;
while ((stringToBreak = infileCust.readLine()) != null) {
     //split up the string with string tokenizer
     StringTokenizer st = new StringTokenizer(stringToBreak);
     firstName = st.nextToken();
     lastName =  st.nextToken();
     custId = Integer.parseInt(st.nextToken());
}
于 2012-02-13T18:54:58.937 回答
0

首先,你想看看你的循环,特别是你如何在循环之外拥有 firstName ,这样你所有的标记都会被扔掉。您将尝试在没有足够信息的情况下创建新的客户对象。

于 2012-02-13T16:55:51.990 回答