我已经看了一段时间,但我无法弄清楚为什么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);
}
}
答案 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
。