Ad_am
Ad_am

Reputation: 23

Switch statement: Random generator

I want to make a quiz with a switch-case statement. Before entering it I generate a random number between 1 and for example 10. Then there are 10 cases, one for each number. In each of them there is a question, meaning, that the program displays a random question at the beginning. When the question is answered correctly i want the program to pick a random question again by generating a number but not the one who was already picked. How do i do that?

Upvotes: 0

Views: 709

Answers (2)

Msp
Msp

Reputation: 2493

You don't have to use switch for this. Try the following code.

public void play() {
    range = new ArrayList<>();
    range.addAll(IntStream.rangeClosed(0, questions.size() - 1).boxed().collect(Collectors.toList()));
    //Assuming 'questions' is an array list of questions

    int index = getQnNumber(); // use this to get a valid question index which is not yet asked
    if(index == -1) //means game over
        System.out.println("Completed");
    else
        askQuestion(index);
}

private int getQnNumber() {
    int size = range.size();
    if(size < 1)
        return -1;
    Random r = new Random();
    int index = r.nextInt(size);
    int questionNumber = range.get(index);
    range.remove(index);
    return questionNumber;
}

Upvotes: 1

Shubhankar S
Shubhankar S

Reputation: 460

You can maintain an ArrayList of the numbers that have been generated already. On every new random generation,

if(!myList.contains(newRandom)){
    return newRandom;
}else{
    //generate a new random and check
}

Upvotes: 0

Related Questions