简体   繁体   English

文本文件解析器无法正常工作Java

[英]Text file parser work incorrectly java

I have text file parser. 我有文本文件解析器。 And with record like 和像这样的记录

1111 SMITH ROBERT J 1900 1111史密斯·罗伯特·J 1900

work correctly and result is 工作正常,结果是

ID: 1111 
LAST NAME: SMITH 
FIRST NAME: ROBERT
MIDDLE NAME: J
MONEY: 1900

But if middle name is empty then result is 但是如果中间名为空,则结果为

ID: 1111 
LAST NAME: SMITH 
FIRST NAME: ROBERT
MIDDLE NAME: 1900
MONEY: 1900

Code: 码:

StringTokenizer st = new StringTokenizer(token);
Client client = new Client();
while(st.hasMoreElements()){
    String token2 = st.nextElement().toString();
    String[] array = new String[5];
    int i = 0;
    array[i++] = new String(token2);

    String id = array[0];
    String lastName = array[1];
    String firstName = array[2];
    String middleName = array[3];
    String money = array[4];
    client.add(id);
    client.add(lastName);
    client.add(firstName);
    client.add(middleName);
    client.add(money);
}
listResult.add(client);

How i can fix it? 我该如何解决?

If money has a specific format (like in our case, where it seems to be a number), then you can backtrack: 如果货币具有特定格式(例如在我们的例子中,它似乎是一个数字),那么您可以回溯:

  • you read N values per line 您每行读取N个值
  • if N = 5, then you're done 如果N = 5,那么您就完成了
  • if N = 4, you can check if array[3] is a number, in that case you shift values (eg: array[4] = array[3], array[3] = "") otherwise array[4] = 0 ("no money"). 如果N = 4,则可以检查array [3]是否为数字,在这种情况下,您可以移动值(例如:array [4] = array [3],array [3] =“”),否则array [4] = 0(“没有钱”)。
  • for other values of N, you have to decide what to do. 对于N的其他值,您必须决定要做什么。

By the way, your code smells bad: 顺便说一句,您的代码难闻:

String token2 = st.nextElement().toString();
String[] array = new String[4];
int i = 0;
array[i++] = new String(token2);
  1. token2 is already a String , there is no need to call new String(token2) . token2已经是一个String ,无需调用new String(token2)
  2. int i = 0; array[i++] int i = 0; array[i++] => will always write the same value. int i = 0; array[i++] =>将始终写入相同的值。
  3. You can reuse the array (eg: put the line 2 before the loop) using Arrays.fill(array, null) thus avoiding new object allocation. 您可以使用Arrays.fill(array, null)重用数组(例如:将第2行放在循环之前) Arrays.fill(array, null)从而避免分配新对象。
  4. You should call your method setFirstName , setLastName , etc on your Client class, and not do something that looks like a List but is not a List . 您应该在Client类上调用方法setFirstNamesetLastName等,而不要执行看起来像List而不是List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM