简体   繁体   中英

3 Lines only about for loop, very confused

why is the output 22212345?

Shouldn't it be: "43212345", because when we are keep adding the first values of the string onto the previous version of the string.

So everytime we increment k, we are going from 2,3,4 and adding it onto the previous version.

why is the output 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.

No, you're not. You're prefixing str with the char at k .

So, if we get a pen and piece of paper and desk check the code (why don't people desk check anymore 😓) you will see what's actually happening...

+---+-----------+---------+-----------------------+
| k | char at k |   str   | result (charAt + str) |
+---+-----------+---------+-----------------------+
| 1 |         2 |   12345 |                212345 |
| 2 |         2 |  212345 |               2212345 |
| 3 |         2 | 2212345 |              22212345 |
+---+-----------+---------+-----------------------+

This happends in each iteration:

first_loop_state: {
    k : 1
    initial_str : "12345";
    str.charAt(k) : '2'
    final_str : "212345"
}
second_loop_state:{
    k : 2
    initial_str : "212345";
    str.charAt(k) : '2'
    final_str : "2212345"
}
 third_loop_state:{
    k : 3
    initial str : "2212345";
    str.charAt(k) : '2'
    final_str : "22212345"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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