Search code examples
javabukkit

Can I make this switch statement any smaller? Preferably with a for loop


Is there a way to make this smaller, I tried using a for loop but couldn't make a random instance for each of the possible Types.

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;
}

Solution

  • you can use .values()

    Random randFireworkEffect = new Random();
    e = FireworkEffect.builder()
            .flicker(true)
            .withColor(c)
            .withFade(c)
            .with(FireworkEffect.Type.values([randFireworkEffect.nextInt(5)])
            .trail(true)
            .build();