gpt4 book ai didi

java - 如何减少这段代码中的 if else 语句?

转载 作者:行者123 更新时间:2023-11-29 07:23:45 28 4
gpt4 key购买 nike

这里的代码基本上是用来根据掷骰子来决定字符串的。这里面有很多陈述,我真的可以使用一些帮助来减少它。我在网上看了一些方法,但都不适合。

public String generatePassageSection(){
int roll = roll();
if(roll<=2 && roll>=1)
{
return "passage goes straight for 10 feet.";
}

else if(roll<=5 && roll>=3)
{
return "passage ends in door to a chamber.";
}

else if(roll<=7 && roll>=6)
{
return "door to right (main passage continues straight for 10 ft)";
}

else if(roll<=9 && roll>=8)
{
return "door to left (main passage continues straight for 10 ft)";
}

else if(roll<=11 && roll>=10)
{
return "passage turns to left and continues for 10 ft";
}

else if(roll<=13 && roll>=12)
{
return "passage turns to right and continues for 10 ft";
}

else if(roll<=16 && roll>=14)
{
return "passage ends in door to chamber";
}

else if(roll==17)
{
return "Stairs, (passage continues straight for 10 ft)";
}

else if (roll<=19 && roll>=18)
{
return "Dead end";
}

else if(roll==20)
{
return "Wandering Monster (passage continues straight for 10 ft)";
}

else
{
return null;
}

最佳答案

这是一个非常好的问题。因为每个 if-else 都是相同的;您检查某个滚动是否在某个范围内,然后返回一个字符串,您可以只使用枚举。可以改进枚举名称以及元素名称,相对于您正在处理和使用此数据表示的内容。

    public String generatePassageSection() {
int roll = roll();

Message message = Stream.of(Message.values()).filter(m -> m.inBounds(roll)).findAny().orElse(null);

return message == null ? null : message.message;
}

enum Message {
FIRST(1, 2, "passage goes straight for 10 feed."),
SECOND(3, 5, "passage ends in the door to a chamber."),
THIRD(6, 7, "door to right (main passage continues straight for 10 ft)"),
FOURTH(9, 10, "door to left (main passage continues straight for 10 ft)"),
FIFTH(10, 11, "passage turns to left and continues for 10 ft"),
SIXTH(12, 13, "passage turns to right and continues for 10 ft"),
SEVENTH(14, 16, "passage ends in door to chamber"),
EIGHTH(17, 17, "Stairs, (passage continues straight for 10 ft)"),
NINTH(18, 19, "Dead end"),
TENTH(20, 20, "Wandering Monster (passage continues straight for 10 ft)");

;
private final int minimumRollInclusive;

private final int maximumRollInclusive;

private final String message;

Message(int minimumRollInclusive, int maximumRollInclusive, String message) {
this.minimumRollInclusive = minimumRollInclusive;
this.maximumRollInclusive = maximumRollInclusive;
this.message = message;
}

boolean inBounds(int roll) {
return roll >= minimumRollInclusive && roll <= maximumRollInclusive;
}

}

int roll() {
return 0; // use ur code
}

此外,应该注意 Enum#values 每次调用时都会创建一个新的数组对象,因此值得缓存它。

关于java - 如何减少这段代码中的 if else 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58579897/

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