我正在创建Android测验应用。我已将其问题随机化,但有时会重复生成的问题。
如何在显示所有问题后防止其重复并终止其方法?
以下是整个工作代码:
public class MainActivity extends Activity {
private int currentQuestion;
private String [] questions;
private String [] answers;
private Button answerButton;
private Button questionButton;
private TextView questionView;
private TextView answerView;
private EditText answerText;
Random random = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
public void init() {
questions = new String[]{"Q1?","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"};
currentQuestion = random.nextInt(questions.length);
answers = new String[]{"A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"};
answerButton = (Button)findViewById(R.id.AnswerButton);
questionButton = (Button)findViewById(R.id.QuestionButton);
questionView = (TextView) findViewById(R.id.QuestionTextView);
answerView = (TextView) findViewById(R.id.AnswerTextView);
answerText = (EditText) findViewById(R.id.AnswerText);
answerButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {checkAnswer();
}});
questionButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
showQuestion();
}});
}
public int showQuestion(){
currentQuestion++;
if(currentQuestion == questions.length);
currentQuestion = 0;
currentQuestion = (random.nextInt(questions.length));
questionView.setText(questions[currentQuestion]);
answerView.setText("");
answerText.setText("");
return currentQuestion;
}
public void checkAnswer() {
String answer = answerText.getText().toString();
if(isCorrect(answer))
answerView.setText("You're right!");
else answerView.setText("Sorry, the correct answer is "+answers[currentQuestion]);
}
}
答案 0 :(得分:2)
答案 1 :(得分:2)
使用Fisher-Yates shuffle在使用之前对questions
和answers
进行随机播放。
static void fyShuffle(String[] questions, String[] answers)
{
Random rnd = new Random();
for (int i = questions.length - 1; i > 0; --i){
int index = rnd.nextInt(i + 1);
// Swap questions
String s = questions[index];
questions[index] = questions[i];
questions[i] = s;
// Swap answers
s = answers[index];
answers[index] = answers[i];
answers[i] = s;
}
}
请参阅http://en.wikipedia.org/wiki/Fisher-Yates_shuffle
它具有所需的特性,即在初始化(即O(N))之后,阵列访问时间是恒定的。拒绝重新绘制元素的算法往往会减慢,因此不能很好地扩展。
答案 2 :(得分:1)
您可以使用不包含重复项(HashSet
)的集合,并使用它而不是String[]
。如果你想要String []数组,你可以从HashSet的内容