gpt4 book ai didi

java - 尝试减少/优化 if/else block 以提高可读性

转载 作者:行者123 更新时间:2023-12-02 06:05:23 24 4
gpt4 key购买 nike

我有以下代码块。基本上,它决定了棒球中一名球员是否获得了多个垒,以及根据某人是否在第一/第二/第三上垒而发生的情况。我用蛮力做到了这一点,但是有没有办法重写它以大幅减少行数?我一直没能想出一个好的方法来做到这一点。

    int runsScored = 0;
switch (action) {
case 0:
break;
case 1:
if (third) {
if (second) {
if (first) {
runsScored = 2;
second = false;
} else {
runsScored = 2;
first = true;
second = false;
third = false;
}
} else {
if (first) {
runsScored = 1;
second = true;
third = false;
} else {
runsScored = 1;
first = true;
third = false;
}
}
} else {
if (second) {
if (first) {
third = true;
} else {
first = true;
}
} else {
if (first) {
second = true;
} else {
first = true;
}
}
}
break;
case 2:
if (third) {
if (second) {
if (first) {
runsScored = 2;
first = false;
} else {
runsScored = 2;
third = false;
}
} else {
if (first) {
runsScored = 1;
second = true;
} else {
runsScored = 1;
second = true;
third = false;
}
}
} else {
if (second) {
if (first) {
runsScored = 1;
third = true;
second = true;
first = false;
} else {
runsScored = 1;
}
} else {
if (first) {
first = false;
second = true;
third = true;
} else {
second = true;
}
}
}
break;
case 3:
if (third) {
if (second) {
if (first) {
runsScored = 3;
first = false;
second = false;
third = true;
} else {
runsScored = 2;
second = false;
}
} else {
if (first) {
runsScored = 2;
first = false;
} else {
runsScored = 1;
}
}
} else {
if (second) {
if (first) {
runsScored = 2;
third = true;
second = false;
first = false;
} else {
runsScored = 1;
second = false;
third = true;
}
} else {
if (first) {
runsScored = 1;
first = false;
second = false;
third = true;
} else {
third = true;
}
}
}
break;
case 4:
if (third) {
if (second) {
if (first) {
runsScored = 4;
first = false;
second = false;
third = false;
} else {
runsScored = 3;
second = false;
third = false;
}
} else {
if (first) {
runsScored = 3;
first = false;
third = false;
} else {
runsScored = 2;
third = false;
}
}
} else {
if (second) {
if (first) {
runsScored = 3;
third = false;
second = false;
first = false;
} else {
runsScored = 2;
second = false;
third = false;
}
} else {
if (first) {
runsScored = 2;
first = false;
second = false;
third = false;
} else {
runsScored = 1;
}
}
}
break;
default:
throw new AssertionError();
}
return runsScored;

最佳答案

好吧,我会用类来描述这一点并让它自行管理,但这是一个很好的第一步。

        if (third) {
if (second) {
if (first) {
runsScored = 2;
second = false;
} else {
runsScored = 2;
first = true;
second = false;
third = false;
}

if (third) {
if (second) {
runsScored = 2;
second = false;
if (!first) {
first = true;
third = false;
}

即在 else 的两侧分解出相同的代码。一旦你清除了一些灌木丛,一些更简单的东西可能就会变得可见。

关于java - 尝试减少/优化 if/else block 以提高可读性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22337538/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com