如何解决我可以让这个 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();
,
要做到这一点:
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[] types = new Type[]{Type.BALL,Type.BALL_LARGE,Type.BURST,Type.CREEPER,Type.STAR};
Random effect = new Random(5);
e = FireworkEffect.builder().flicker(true)
.withColor(c).withFade(c)
.with(types[effect.nextInt()])
.trail(true).build();
是的,您可以将其放入循环中,以设置更多值。
,有以下最佳做法可以避免出现虚假的 case-statements。首先应该创建一些预定义关系的映射。然后您就可以在运行时从中获取值。
private static final Map<Integer,Type> typeMap = new Hashmap<>();
static {
typeMap.put(0,Type.BALL);
typeMap.put(1,Type.BALL_LARGE);
typeMap.put(2,Type.BURST);
typeMap.put(3,Type.CREEPER);
typeMap.put(4,Type.STAR);
}
public FireworkEffect getFireworkEffect() {
Random randFireworkEffect = new Random(5);
Type type = typeMap.get(randFireworkEffect);
return FireworkEffect.builder()
.flicker(true)
.withColor(c)
.withFade(c)
.with(type)
.trail(true)
.build();
}
,
迭代 .values()
不是最优的。最好使用预填充哈希映射
Map<Integer,Type> typeMap = new HashMap<>();
typeMap.put(0,Type.BALL);
typeMap.put(1,Type.BALL_LARGE);
// ... other options
Random randFireworkEffect = new Random(5);
e = FireworkEffect.builder()
.flicker(true)
.withColor(c)
.withFade(c)
.with(typeMap.get(randFireworkEffect.nextInt()))
.trail(true)
.build();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。