public class Shuffle1 {
public static void main(String[] args) {
int x = 3;
if(x > 2) {
System.out.print("a");
}
while(x > 0) {
x = x - 1;
System.out.print("-");
}
if(x == 2) {
System.out.print("b c");
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
}
我正在从一本名为“Head First Java”的书中学习Java,我正在使用本书中推荐的TextEdit。我应该能够编译代码来获得a-b c-d的答案,但是每次我编译它时,我得到的结果是---。我亲自检查过,如果有人能帮助我,我会非常感激。 Here is the original question from the book.
答案 0 :(得分:1)
因此,如果x
为3,我将带您了解所发生的事情:
x
减少为0,打印" - "在途中,因为它需要2个减量来满足中断条件,x> 0 这意味着它会正确打印a--
。要实现a-b c-d
,必须在循环中使用if语句,如下所示:
while(x > 0) {
x = x - 1;
System.out.print("-");
if(x == 2) {
System.out.print("b c");
}
if(x == 1) {
System.out.print("d");
x = x - 1;
}
}
现在执行周期为:
x
> 2,所以打印" a" x
变为2 x
是2,所以打印" b c" x
变为1 x
为1,因此打印" d" x
现在为0 这会得到以下所需结果:a-b c-d
。
答案 1 :(得分:1)
这将根据您的期望打印。
public class Shuffle1 {
public static void main(String[] args) {
int x = 3;
if(x > 2) { //First time x=3, which is true
System.out.print("a"); // print a
}
while(x > 0) { // x=3, which is true
x = x - 1; //first loop, x=2, then second loop x=1
System.out.print("-"); //prints "-"
if(x == 2) { // x=2, which is true
System.out.print("b c"); //prints "b c"
}
if(x == 1) { // as x=2, so it won't get display in first loop, but when it loop for second time, x become 1, which is true.
System.out.print("d");
x = x - 1;
}
}
}
}