如何将这个程序从if-else-if语句转换为Java中的switch语句?

时间:2017-11-18 18:35:47

标签: java if-statement switch-statement converters

我无法将此程序从if-else-if语句转换为switch语句。

public void tick() {
    if (s.word == 0)
        return;

    short t = this.sc.word;
    short d = this.get_opcode();
    short i = this.get_indirect_bit();

    if (t == 0 || t == 1)
        this.instruction_fetch(t);

    if (t == 2)
        this.instruction_decode();

    if (t == 3 && d != 7)
        this.operand_fetch(i);

    if (t > 3 && d != 7)
        this.execute_mri(d, t);

    if (t == 3 && d == 7) {
        this.execute_rri((short) (this.ir.word & 0xFFF));
    }
}

1 个答案:

答案 0 :(得分:1)

不可能完全消除“if”语句,但此代码应该是您正在寻找的内容:

if (s.word == 0)
    return;
short t = this.sc.word;
short d = this.get_opcode();
short i = this.get_indirect_bit();

switch(t) {
    case 0:
    case 1:
        this.instruction_fetch(t);
        break;
    case 2:
        this.instruction_decode();
        break;
    case 3:
        if(d ==7) {
            this.execute_rri((short) (this.ir.word & 0xFFF));
        }
        else {
            this.operand_fetch(i);
        }
        break;
    default:
        if(d!=7) this.execute_mri(d, t);
        break;
}