Get random element from array without repeats in Java

math.random no repeat java
javascript random array element no repeat
get random element from array java
get random element from arraylist java
select random string from array java
get random element from set java
java 8 random element from list
how to return a random string in java

I'm creating a java GUI based program, and I have an array of questions. I need to create a method that gets the next question after I click a JButton. The next question should be chosen randomly and shouldn't repeat a previously-asked question. See the code below -- how would getNextQuestion be implemented?

public class QuestionBank {

    String [] questions;
    int currQuestionIndex;

    public QuestionBank() {
        questions = new String [10]; //increase array size if you will add more questions
        questions[0]= "Which three words describe you best?";
        questions[1]= "Which is your best feature?";
        questions[2]= "Which common saying or phrase describes you?";
        questions[3]= "What’s the best thing that’s happened to you this week?";
        questions[4]= "Who was your role model when you were a child?";
        questions[5]= "Who was your favorite teacher and why?";
        questions[6]= "What was your favorite subject at school?";
        questions[7]= "What did you want to be when you grew up?";
        questions[8]= "If you could have one wish come true what would it be?";
        questions[9]= "Which would you prefer — three wishes over five years or one wish right now?";
        //add more questions
    }

    public String getNextQuestion() {
        //get the next question, randomly from the array and without repeats
    }
}

If you want to get items from a collection in a random order without repeats (as clarified in the comments), you can first shuffle the collection and then iterate through the collection normally.

In Java it's easier to shuffle an ArrayList compared to an array, so consider the following:

public class QuestionBank {

    List<String> questions;
    int currQuestionIndex;

    public QuestionBank() {
        questions = new ArrayList<>(); // no size needed
        questions.add("Which three words describe you best?");
        questions.add("Which is your best feature?");
        // add more questions
        currQuestionIndex = 0; // it's 0 by default but this makes it explicit
        Collections.shuffle(questions); // shuffle all questions
    }

    public String getNextQuestion() {
        // get the next question, randomly from the list and without repeats
        if (currQuestionIndex >= questions.size()) {
            return null; // no more questions!
        }
        String nextQuestion = questions.get(currQuestionIndex);
        currQuestionIndex++; // move forward in the shuffled list
        return nextQuestion;
    }
}

If you have to use an array instead of a List, see this question on shuffling an array. The rest of the strategy stays the same.

How to randomly pick element from array without repeating?, You could use a List instead, and then remove the element if it is chosen: List<​Question> questions = new ArrayList<Question>(); // For  before storing a random number into the given array we have to consider 2 things. whether array contains desired number of random numbers or not (to print the final array elements) whether the generated random number is existed in the array previously or not. if we achieve those 2 things then we will get the result as you expected

How about using a Queue ?

import java.util.*;

public class QuestionBank {

    static Queue<String> questions;

    public QuestionBank() {
        List<String> tmpQuestions = new ArrayList<>(); // no size needed
        tmpQuestions.add("Which three words describe you best?");
        tmpQuestions.add("Which is your best feature?");
        tmpQuestions.add("Which common saying or phrase describes you?");
        tmpQuestions.add( "What’s the best thing that’s happened to you this week?");
        tmpQuestions.add("Who was your role model when you were a child?");
        tmpQuestions.add("Who was your favorite teacher and why?");
        tmpQuestions.add("What was your favorite subject at school?");
        tmpQuestions.add("What did you want to be when you grew up?");
        tmpQuestions.add("If you could have one wish come true what would it be?");
        tmpQuestions.add( "Which would you prefer — three wishes over five years or one wish right now?");
        Collections.shuffle(tmpQuestions, new Random()); // shuffle all questions

Using ArrayDeque as suggested by pkpnd with the following reason

        questions = new ArrayDeque<>(tmpQuestions); 
    }
    public String getNextQuestion() {
        // get the next question, from the randomly populated queue
        if (questions.isEmpty()) {
            return null; // no more questions!
        }
        return questions.remove();
    }

    public static void main(String[] args) {
        QuestionBank qb = new QuestionBank();
        String question;
        while((question = qb.getNextQuestion()) != null){
            System.out.println(question);
        }
    }
}

And the outputs are:

    // 1st execution
Who was your role model when you were a child?
What?s the best thing that?s happened to you this week?
Which common saying or phrase describes you?
Which is your best feature?
Which three words describe you best?
What was your favorite subject at school?
Which would you prefer ? three wishes over five years or one wish right now?
If you could have one wish come true what would it be?
Who was your favorite teacher and why?
What did you want to be when you grew up?

//2nd execution
Which common saying or phrase describes you?
What did you want to be when you grew up?
What?s the best thing that?s happened to you this week?
Which three words describe you best?
What was your favorite subject at school?
Which would you prefer ? three wishes over five years or one wish right now?
Who was your role model when you were a child?
Which is your best feature?
Who was your favorite teacher and why?
If you could have one wish come true what would it be?

//3rd execution and so on ....
What?s the best thing that?s happened to you this week?
Which common saying or phrase describes you?
Which is your best feature?
What was your favorite subject at school?
Which would you prefer ? three wishes over five years or one wish right now?
If you could have one wish come true what would it be?
What did you want to be when you grew up?
Which three words describe you best?
Who was your role model when you were a child?
Who was your favorite teacher and why?

Java, A quick and practical guide to picking a random item/items from a List in Java. Select Random Items Without Repetitions. Here, you need to  A quick and practical guide to picking a random item/items from a List in Java. Java – Get Random Item/Element From a List. Select Random Items Without

If you want to use the int currQuestionIndex to access the next question in the array, make sure you initialise it in the constructor!

i.e.

public QuestionBank() {
    // Initialise and define 'questions' String array here ...
    this.currQuestionIndex = 0;
}

Assuming you just want to access the current String in the questions array, and then advance to the next question for the next time the method is called:

public String getNextQuestion() {
    // Wrap around when we overshoot the array
    if (currQuestionIndex > questions.length)
        currQuestionIndex = 0;

    currQuestionIndex++;
    return questions[currQuestionIndex-1];
}

Also can select a random question, make sure you import java.util.Random:

public String getRandomQuestion() {
    Random rand = new Random();
    return questions[rand.nextInt(questions.length)];
}

Randomly select items from a List in Java, Java program select a random element from array. import java.util.ArrayList;. import java.util Select Random Items Without Repetitions List Element Sometimes  Find the first non-repeating element in a given array of integers. Examples: Input : -1 2 -1 3 2 Output : 3 Explanation : The first number that does not repeat is : 3 Input : 9 4 9 6 7 4 Output : 6. A Simple Solution is to use two loops.

How to generate random numbers in Java without repetition, How do you randomly select an array element in Java? When you instantiate Shuffler, give it your array as a parameter. It will create a copy of the array and every time next() is called it will return a random element from a copy and remove it from the copy array so that no repeats are possible.

Creating an array of random numbers with no duplicates, How do you generate a random number without repetition in Java? Lemonade takes a flat fee, pays claims super fast, and gives back what’s left to causes you care about. You dismissed this ad. The feedback you provide will help us show you more relevant content in the future. You can use java.util.Random class. For examples on random numbers in java refer this resource.

Random array string that doesn't repeat (Beginning Java forum at , Don't use Math.random to generate random numbers. The last 3 elements of the array are distinct random elements. Some current language runtimes have generators that meet this requirement but none - not Java, not . Java Project Tutorial - Make Login and Register Form Step by Step Using NetBeans And MySQL Database - Duration: 3:43:32. 1BestCsharp blog Recommended for you 3:43:32

Comments
  • Can the questions be repeatable?
  • Increment currQuestionIndex and verify it's not out bounds...
  • @MadProgrammer - you missed 'Randomly from the array...'
  • @zlakad And the difference being?! Sorry finding it hard to see the issue
  • @MadProgrammer check the OP's source code comment
  • The likely hood is the OP isn't allowed to use ArrayList or Set or all the really nice stuff that would make this simple
  • thnk you so much