dimanche 23 février 2020

java: method (in enum) to not to return same names [duplicate]

So basicly I need the getRandomNameCourseAsString() return name of subject, but I call it in for(..), so it can return same subject. I don't want to see same subject twice, so i tried this method but it gives me

java.lang.ArrayIndexOutOfBoundsException: 43

Commented lines is working if replace return

public enum CourseName {
    PHYSICS,
    CHEMISTRY,
    HISTORY,
    UKRAINIAN,
    ENGLSH,
    PROGRAMMING,
    PSYCHOLOGY,
    PHYLOSOPHY,
    OOP,
    COMPUTER_SCIENCE;
    private static final CourseName[] COURSE_NAMES = values();
    private static final int SIZE = COURSE_NAMES.length;
    private static final Random RANDOM = new Random();
    private static ArrayList<Integer> list = new ArrayList<>(SIZE);


    //can return same subject if: return COURSE_NAMES[RANDOM.nextInt(SIZE)];
    public static CourseName getRandomCourseName()  {
        return COURSE_NAMES[Rand(list)];
    }

    //want it to not return same subject by this method
    private static int Rand(ArrayList<Integer> list){
        for(int i = 1; i <= SIZE; i++) {
            list.add(i);
        }
        int index = RANDOM.nextInt(list.size());
        list.remove(index);
        return index;

    }
    public static String getRandomNameCourseAsString(){
        return String.valueOf(CourseName.getRandomCourseName());
    }
}



Aucun commentaire:

Enregistrer un commentaire