【问题标题】:string tokenizer stopping after first line字符串标记器在第一行后停止
【发布时间】:2012-02-13 16:47:24
【问题描述】:

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

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

            }


    }

【问题讨论】:

  • 我应该为每个变量声明使用 camelCase。在您的代码中,StringToBreakCustomerObject 具有首字母大写字母,这是为类型(类和接口)保留的。它有效,但会导致混乱。

标签: java stringtokenizer


【解决方案1】:
String StringToBreak = infileCust.readLine();

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

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

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;

【讨论】:

  • 好的,我完全明白你在说什么,但是我在编写外循环时遇到了麻烦。我的外循环几乎就是这样:while (infileCust.readLine() != null) {
  • 消耗当前行是什么意思?
  • 最后你说我不需要内部循环,所以我猜我只需要告诉标记器“使用”该行,但我不知道方法并且可以'好像没找到..
【解决方案2】:

对于外循环,您需要将当前行的内容存储在 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());
}

【讨论】:

  • 我必须添加 StringTokenizer st = new StringTokenizer(stringToBreak);就在while循环之前,不是吗?我收到一个错误:线程“main”中的异常 java.lang.NullPointerException
  • 感谢您的编辑。这看起来不错,但现在它只是打印一个空行而不是 1
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-28
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2019-09-23
    相关资源
    最近更新 更多