尽量减少使用if语句

时间:2015-11-03 22:01:51

标签: java if-statement

我试图在以下if语句中尽量减少条件语句,如何实现?

if(safeHalFromCros == true){
        System.out.println("Crossbowman cannot win, Halbedier out of range");
        if(speedHalToCav < speedCavToCros){
            halberdier.setXPos(cavalier.getXPos());
            halberdier.setYPos(cavalier.getYPos());
            System.out.printf("***The winner is: %3s:\n",halberdier.toString());

        }else{
            cavalier.setXPos(crossBowMan.getXPos());
            cavalier.setYPos(crossBowMan.getYPos());
            System.out.printf("***The winner is %3s:\n",cavalier.toString());
            crossBowMan.setXPos(-1.0);
            crossBowMan.setYPos(-1.0);

        }
    }else{
        System.out.println("Crossbowman has a chance to win, Halbedier is within range");
        if(speedCrosToHal < speedHalToCav && speedCrosToHal < speedCavToCros){
            System.out.println("Printing out the speeds for testing purposes");
            System.out.println("Speed of crossbowman to halberdier is: "+speedCrosToHal);
            System.out.println("Speed of halbedier to cavalier is: "+speedHalToCav);
            System.out.println("Speed of cavalier to crossbowman is: "+speedCavToCros);
            halberdier.setXPos(-1.0);
            halberdier.setYPos(-1.0);
            System.out.printf("***The winner is %3s:\n",crossBowMan.toString());
        }
    }

3 个答案:

答案 0 :(得分:0)

您需要使用开放原则或策略模式

答案 1 :(得分:0)

使用? :Java中的运算符(如果您不想使用“if” - 虽然实现相同)

答案 2 :(得分:0)

我认为你的代码很好。但是如果你的代码是一个完整的方法(不仅仅是方法的一部分),你可以使用这种技术。再说那不是我在这里会做的,但有时它会非常有用。

if(!safeHalFromCros) {
    System.out.println("Crossbowman has a chance to win, Halbedier is within range");
    //...
    return;
}
if(speedHalToCav < speedCavToCros){
    //...
    System.out.printf("***The winner is: %3s:\n",halberdier.toString());
    return;
}
//...
System.out.printf("***The winner is %3s:\n",cavalier.toString());