简体   繁体   English

为什么以下代码显示“ 0 1 2 3”?

[英]Why does the following code print “0 1 2 3”?

in this code im confused as to why it prints out "0 1 2 3" instead of "3 2 1 0" 在这段代码中,我对为什么打印出“ 0 1 2 3”而不是“ 3 2 1 0”感到困惑

    int y = 3;
    String s = " ";
    while (y>-1)
    {
        s = y + " " + s;
        y--;
    }
    System.out.print(s);

Thanks. 谢谢。

s = y + " " + s;

adds y at the front of the string so: 在字符串的前面加上y,这样:

s = 3 
s = 2 3
s = 1 2 3
s = 0 1 2 3
step 1:
s = 3

step 2:
s = 2 3;

step 3:
s = 1 2 3

like wise in every loop y's value is added to the starting point of the string s 就像在每个循环中一样,将y的值添加到字符串s的起点

This is because you prepend the newest value to the string. 这是因为您将最新值放在字符串之前。 If you want the output to be "3 2 1 0" you should change your line from 如果您希望输出为“ 3 2 1 0”,则应从

s = y + " " + s;

to

s = s + " " + y;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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