Languages
[Edit]
PL

Java - pobierz losowy element z enum

6 points
Created by:
Sylwia
1327

1. Generuj losowe wyliczenie z klasą Random

import java.util.Random;

public class JavaEnumGetRandomElement {

    enum ColorEnum {
        GREEN,
        BLUE,
        RED,
        YELLOW;

        public static ColorEnum generateRandomColor() {
            ColorEnum[] values = ColorEnum.values();
            int length = values.length;
            int randIndex = new Random().nextInt(length);
            return values[randIndex];
        }
    }

    public static void main(String[] args) {
        System.out.println(ColorEnum.generateRandomColor()); // CZERWONY
        System.out.println(ColorEnum.generateRandomColor()); // ŻÓŁTY
        System.out.println(ColorEnum.generateRandomColor()); // ZIELONY
    }
}
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.