By far the simplest way to achieve this (but not what I recommend) is to use an Arraylist
of String
s and then remove the used questions as you go
public class Test {
public static void main(String[] args) {
Random rnd=new Random();
ArrayList<String> questions = new ArrayList<String>();
ArrayList<Boolean> answers = new ArrayList<Boolean>();
questions.add("Question 1");
answers.add(true);
questions.add("Question 2");
answers.add(false);
while (array.isEmpty()==false){
int index=rnd.nextInt(questions.size());
String question=questions.get(index);
boolean answer=answers.get(index);
questions.remove(index);
answer.remove(index);
//do whatever with the question
}
}
}
Object orientated alternative
A nicer object orientated way to do this, however, would be to create an object to hold the question and answer together
public class QAndA {
public final String question;
public final boolean answer;
public QAndA(String question, boolean answer) {
this.question = question;
this.answer = answer;
}
}
And then hold those objects in an Arraylist
public class Test {
public static void main(String[] args) {
Random rnd=new Random();
ArrayList<QAndA> array = new ArrayList<QAndA>();
array.add(new QAndA("Question 1",true));
array.add(new QAndA("Question 2",true));
while (array.isEmpty()==false){
int index=rnd.nextInt(array.size());
QAndA question=array.get(index);
array.remove(index);
//do whatever with the question
}
}
}
Removing objects from an Arraylist
is not a very quick option but given that the Arraylist
is probably short this is unlikely to be an important factor. If it is consider some of the other collections. The fields in QAndA
are declared public
as the QAndA
class is a glorified struct, again consider whether this is appropriate dependant on your usage.