猿问

? 多个 ifs/cleaner 代码的运算符

所以我在完成的项目中有这部分代码:


        if (mode == 1) {                    

        repeats = 2;

        columns = 6;

        size = 24;

    }

    else if (mode == 2) {               

        repeats = 2;

        columns = 8;

        size = 48;

    }

    else if (mode == 3) {               

        repeats = 3;

        columns = 6;

        size = 36;

    }

我只是弄乱了它,我想知道是否有更好的方法来使用 ? 运营商或任何其他方式。


开满天机
浏览 124回答 3
3回答

智慧大石

我会将int[][]每个值定义mode为一个键。喜欢,int[][] modes = { {}, { 2, 6, 24 }, { 2, 8, 48 }, { 3, 6, 36 } };if (mode > 0 && mode < 4) {&nbsp; &nbsp; repeats = modes[mode][0];&nbsp; &nbsp; columns = modes[mode][1];&nbsp; &nbsp; size = modes[mode][2];}

动漫人物

使用三元 ?&nbsp;运算符将不起作用,因为您要根据 的值更新太多变量mode。如果你用过?那么您一次只能在一个变量上使用它,并且代码将非常繁琐且难以阅读。切换是最好的选择

PIPIONE

最好的擦除方法if是使用多态。对于给定的代码,您可以抽象一个类或一个接口并以不同的方式实现该方法。示例代码如下。public class Test {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; int modeValue = 1;//2,3 ...&nbsp; &nbsp; &nbsp; &nbsp; ModeFactory modeFactory = new ModeFactory();&nbsp; &nbsp; &nbsp; &nbsp; Mode mode = modeFactory.generateMode(modeValue);&nbsp; &nbsp; &nbsp; &nbsp; mode.fillData();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("mode info:" + mode.toString());&nbsp; &nbsp; }}abstract class Mode {&nbsp; &nbsp; int repeats;&nbsp; &nbsp; int columns;&nbsp; &nbsp; int size;&nbsp; &nbsp; abstract void fillData();&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return "Mode{" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "repeats=" + repeats +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ", columns=" + columns +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ", size=" + size +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; '}';&nbsp; &nbsp; }}class Mode1 extends Mode {&nbsp; &nbsp; @Override&nbsp; &nbsp; void fillData() {&nbsp; &nbsp; &nbsp; &nbsp; repeats = 2;&nbsp; &nbsp; &nbsp; &nbsp; columns = 6;&nbsp; &nbsp; &nbsp; &nbsp; size = 24;&nbsp; &nbsp; }}class Mode2 extends Mode {&nbsp; &nbsp; @Override&nbsp; &nbsp; void fillData() {&nbsp; &nbsp; &nbsp; &nbsp; repeats = 2;&nbsp; &nbsp; &nbsp; &nbsp; columns = 8;&nbsp; &nbsp; &nbsp; &nbsp; size = 48;&nbsp; &nbsp; }}class Mode3 extends Mode {&nbsp; &nbsp; @Override&nbsp; &nbsp; void fillData() {&nbsp; &nbsp; &nbsp; &nbsp; repeats = 3;&nbsp; &nbsp; &nbsp; &nbsp; columns = 6;&nbsp; &nbsp; &nbsp; &nbsp; size = 36;&nbsp; &nbsp; }}class ModeFactory {&nbsp; &nbsp; Mode generateMode(int modeValue) {&nbsp; &nbsp; &nbsp; &nbsp; if (modeValue == 1) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Mode1();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (modeValue == 2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return new Mode2();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return new Mode3();&nbsp; &nbsp; }}design patterns 可以帮助您解决这些问题。
随时随地看视频慕课网APP

相关分类

Java
我要回答