有人可以解释一下为什么我的循环从0到7?我只需要在前3个案例中获得,但程序正在通过所有..代码在show()方法中。
for(brojac=0; brojac<3; brojac++){
switch(brojac){
case 1:
figura1.setPosition(pomx[random], pomy[random]);
stage.addActor(figura1);
System.out.println("1");
case 2:
figura2.setPosition(pomx[random], pomy[random]);
stage.addActor(figura2);
System.out.println("2");
case 3:
figura3.setPosition(pomx[random], pomy[random]);
stage.addActor(figura3);
System.out.println("3");
case 4:
figura4.setPosition(pomx[random], pomy[random]);
stage.addActor(figura4);
System.out.println("4");
case 5:
figura5.setPosition(pomx[random], pomy[random]);
stage.addActor(figura5);
System.out.println("5");
case 6:
figura6.setPosition(pomx[random], pomy[random]);
stage.addActor(figura6);
System.out.println("6");
case 7:
figura7.setPosition(pomx[random], pomy[random]);
stage.addActor(figura7);
System.out.println("7");
}
}
答案 0 :(得分:4)
因为缺少休息时间。在每个案例之后,您需要break关键字。有关详细说明,请参阅switch statement java tutorial
e.g。
for(brojac=0; brojac<3; brojac++){
switch(brojac){
case 1:
figura1.setPosition(pomx[random], pomy[random]);
stage.addActor(figura1);
System.out.println("1");
break; /// Break here
case 2:
figura2.setPosition(pomx[random], pomy[random]);
stage.addActor(figura2);
System.out.println("2");
break; /// Break here
case 3:
figura3.setPosition(pomx[random], pomy[random]);
stage.addActor(figura3);
System.out.println("3");
break; /// Break here
case 4:
figura4.setPosition(pomx[random], pomy[random]);
stage.addActor(figura4);
System.out.println("4");
break; /// Break here
case 5:
figura5.setPosition(pomx[random], pomy[random]);
stage.addActor(figura5);
System.out.println("5");
break; /// Break here
case 6:
figura6.setPosition(pomx[random], pomy[random]);
stage.addActor(figura6);
System.out.println("6");
break; /// Break here
case 7:
figura7.setPosition(pomx[random], pomy[random]);
stage.addActor(figura7);
System.out.println("7");
break; /// Break here
}
}
否则,如果上述案例之一被评估为真,则将执行其他案例。
答案 1 :(得分:1)
这就是Java's switch
陈述的工作原理。
一旦其中一个匹配,他们就会“落伍”。您需要在所有情况之后添加break;
。
for(brojac=0; brojac<3; brojac++){
switch(brojac){
case 1:
figura1.setPosition(pomx[random], pomy[random]);
stage.addActor(figura1);
System.out.println("1");
break;
case 2:
figura2.setPosition(pomx[random], pomy[random]);
stage.addActor(figura2);
System.out.println("2");
break;
case 3:
figura3.setPosition(pomx[random], pomy[random]);
stage.addActor(figura3);
System.out.println("3");
break;
case 4:
figura4.setPosition(pomx[random], pomy[random]);
stage.addActor(figura4);
System.out.println("4");
break;
case 5:
figura5.setPosition(pomx[random], pomy[random]);
stage.addActor(figura5);
System.out.println("5");
break;
case 6:
figura6.setPosition(pomx[random], pomy[random]);
stage.addActor(figura6);
System.out.println("6");
break;
case 7:
figura7.setPosition(pomx[random], pomy[random]);
stage.addActor(figura7);
System.out.println("7");
break;
}
}