经过一个while循环后,为什么赢得了我的字符串更新?

时间:2015-09-27 19:20:40

标签: java string loops while-loop

我已经看了一段时间,但我无法弄清楚为什么paddedTime不会打印出来" 0530"。我显然缺少一些东西。提前谢谢!

public class TestString {

    public static void main(String[] args) {
        String time = "530";
        String paddedTime = "";
        while (time.length() < 4) {
            time = "0" + time;
        }
        if (time.length() == 4) {
            time = paddedTime;
        }
        System.out.println(paddedTime);
    }
}

2 个答案:

答案 0 :(得分:3)

除了paddedTime之外,您永远不会将值分配给""。但是,这应该有效:

    String time = "530";
    String paddedTime = "";
    while (time.length() < 4) {
        time = "0" + time;
    }
    if (time.length() == 4) {
        paddedTime = time;
    }
    System.out.println(paddedTime);

答案 1 :(得分:3)

应该是

if (time.length() == 4) {
        paddedTime = time;//to assign time value to paddedTime
    }

有了这个

time = paddedTime;

您要将空字符串分配给time