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 がそれ以上のトークンを見つけられないのは正常です。

すべての行を読み取るには、これをすべて囲む 2 番目のループを作成する必要があります。それは:

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

実際、3 つの異なるフィールドがあるため、内部ループを実行する必要はありません。それは十分です:

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 に答える