[英]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: 如果货币具有特定格式(例如在我们的例子中,它似乎是一个数字),那么您可以回溯:
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);
token2
is already a String
, there is no need to call new String(token2)
. token2
已经是一个String
,无需调用new String(token2)
。 int i = 0; array[i++]
int i = 0; array[i++]
=> will always write the same value. int i = 0; array[i++]
=>将始终写入相同的值。 Arrays.fill(array, null)
thus avoiding new object allocation. 您可以使用Arrays.fill(array, null)
重用数组(例如:将第2行放在循环之前) Arrays.fill(array, null)
从而避免分配新对象。 setFirstName
, setLastName
, etc on your Client class, and not do something that looks like a List
but is not a List
. 您应该在Client类上调用方法setFirstName
, setLastName
等,而不要执行看起来像List
而不是List
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.