在java(android)中生成随机数组String []而不重复

时间:2014-01-06 09:38:56

标签: java android string repeat

我正在创建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]);
}
}

3 个答案:

答案 0 :(得分:2)

  1. 给每个问题一个数字(int)并假设你有10个问题。
  2. 生成1到10之间的随机数。
  3. 创建一个集合来跟踪您的问题(最好列出..)
  4. 每次生成随机数时,请检查集合是否已包含该数字。 如果是,请生成另一个随机数,否则将其添加到集合中..

答案 1 :(得分:2)

使用Fisher-Yates shuffle在使用之前对questionsanswers进行随机播放。

 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的内容

轻松创建它