【发布时间】:2021-09-16 19:59:04
【问题描述】:
有没有办法让这个更小,我尝试使用 for 循环,但无法为每个可能的类型创建一个随机实例。
Random randFireworkEffect = new Random(5);
switch(randFireworkEffect.nextInt()) {
case 0:
e = FireworkEffect.builder().flicker(true).withColor(c).withFade(c).with(Type.BALL).trail(true).build();
break;
case 1:
e = FireworkEffect.builder().flicker(true).withColor(c).withFade(c).with(Type.BALL_LARGE).trail(true).build();
break;
case 2:
e = FireworkEffect.builder().flicker(true).withColor(c).withFade(c).with(Type.BURST).trail(true).build();
break;
case 3:
e = FireworkEffect.builder().flicker(true).withColor(c).withFade(c).with(Type.CREEPER).trail(true).build();
break;
case 4:
e = FireworkEffect.builder().flicker(true).withColor(c).withFade(c).with(Type.STAR).trail(true).build();
break;
}
【问题讨论】:
-
是的,要短得多,但这里我们讨论的是代码审查
-
你有很多代码重复。所有这些情况之间唯一不同的是您选择的
Type枚举。您应该将其放入变量中,然后在switch之后执行其余代码。所以Type type = switch(...) { case 0 -> Type.BALL; case 1 -> ... };然后...with(type)...。 -
您只是想将
int转换为FireworkEffect.Type枚举,所以this 应该会有所帮助。根本不需要 switch 语句或循环。 -
我投票结束这个问题,因为它属于Code Review。