我有以下文件,我将其用作测试:
ID = 1392
名称=弥敦道
gender = male的
testempty =
testempty2 =
拉链= 11111
我在循环行并调用函数processLine(String line)
来处理Strings
:
private String processLine(String line) {
Scanner scanner = new Scanner(line);
StringBuilder result = new StringBuilder();
scanner.useDelimiter("=");
if (scanner.hasNext()) {
result.append(scanner.next());
result.append(" , ");
result.append(scanner.next());
result.append(" , ");
}
return result.toString();
}
但我如何能够检测到下一个是否没有(例如testempty
上)并执行result.append("empty , ")
?
答案 0 :(得分:1)
(我认为这就是你所要求的)
更改行:
result.append(scanner.next());
为:
result.append(scanner.hasNext() ? scanner.next() : "empty");
答案 1 :(得分:1)
更改方法。如果结果不为空,则在附加值之前附加“,”:
if (scanner.hasNext()) {
if (!result.isEmpty()) {
result.append(" , ");
}
result.append(scanner.next());
result.append(" , ");
result.append(scanner.next());
}