与StringBuilder不一致在循环中追加

时间:2017-05-01 19:58:47

标签: loops append iteration stringbuilder

我在循环中使用StringBuilder时出现问题,因为输出不一致。请帮忙!!!

String oldStr = "job1.job2.job3";
String[] newStr = oldStr.split(Pattern.quote("."));
StringBuilder result = new StringBuilder();
for (String temp : newStr) {    
    String key = "This is "+keyStr+" ,";
    result.append(key);
    System.out.println(key.toString());
}

我希望结果是

This is job1.  
This is job1.  This is job2.
This is job1.  This is job2.  This is job3.

我确实在某个时刻看到了预期的结果,但我现在看到了这些:

This is job1.  
This is job2.  
This is job3.

如果我继续运行代码,我会看到多个元素:

This is job1.  
This is job2.  
This is job3.
This is job1.  
This is job2.  
This is job3.

我的代码是否存在问题,或者StringBuilder的行为不正确? TIA。

1 个答案:

答案 0 :(得分:0)

更改此行

System.out.println(key.toString());

System.out.println(result.toString());