为什么输出是22212345?
不应该是:“43212345”,因为当我们不断将字符串的第一个值添加到字符串的先前版本中时。
因此每次我们增加 k 时,我们都会从 2,3,4 开始并将其添加到之前的版本中。
为什么输出是22212345?
String str = "12345";
for (int k = 1; k <= 3; k++)
str = str.charAt(k) + str;
最佳答案
So everytime we increment k, we are going from 2,3,4 and adding it onto the previous version.
不,你不是。您在 str
前面添加了 k
处的字符。
所以,如果我们拿出一支笔和一张纸并在办公 table 上检查代码(为什么人们不再在办公 table 上检查😓),您就会看到实际发生了什么......
+---+-----------+---------+-----------------------+
| k | char at k | str | result (charAt + str) |
+---+-----------+---------+-----------------------+
| 1 | 2 | 12345 | 212345 |
| 2 | 2 | 212345 | 2212345 |
| 3 | 2 | 2212345 | 22212345 |
+---+-----------+---------+-----------------------+
关于java - 3行只有for循环,很困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59978478/