我可以让这个switch语句更小吗?最好有for循环
有没有办法让它更小,我尝试使用 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;
}
回答
您可以使用 .values()
Random randFireworkEffect = new Random();
e = FireworkEffect.builder()
.flicker(true)
.withColor(c)
.withFade(c)
.with(FireworkEffect.Type.values([randFireworkEffect.nextInt(5)])
.trail(true)
.build();