如何从数组中随机选择元素而不重复? [英] How to randomly pick element from array without repeating?
本文介绍了如何从数组中随机选择元素而不重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发测验应用程序.我设法用
I am working on an quiz app. I managed to randomized the questions(from an array) with
int position = new Random().nextInt(questions.length);
,但问题不断重复.我要如何在到达10个问题时不再重复重复说明?这是我的代码,如果有帮助的话:
but the questions keep on repeating. How do i make it stop getting when it reaches lets say 10 questions without repeating? Here is my code if it helps:
gcfQuiz.setText(questions[position]);
gcfButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Answer = (EditText) findViewById(R.id.txtAns1);
String finAns = Answer.getText().toString();
if (finAns==answers[position]){
correct++;
}
position++;
if (position<questions.length)
{
gcfQuiz.setText(questions[position]);
}else {
Intent in = new Intent(getApplicationContext(), gcfResult.class);
startActivity(in);
}
}
});
推荐答案
您可以改用 List
,然后删除该元素(如果已选择):
You could use a List
instead, and then remove the element if it is chosen:
List<Question> questions = new ArrayList<Question>();
// For Question class, see below.
// Get some random valid index from the list.
int index = new Random().nextInt(questions.size());
// Remove the question from the list and store it into a variable.
Question currQuestion = questions.remove(i);
为您提供信息,我假设 Question
类看起来像这样.通常,此方法比分别具有问题和答案的两个单独的数组要好:
For your information, I assumed the Question
class looks like this. This approach is generally better than two separate arrays with questions and answers respectively:
class Question {
private String text;
private String answer;
public Question(String text, String answer) {
this.text = text;
this.answer = answer;
}
public boolean isCorrectAnswer(String inputAnswer) {
return Objects.equals(answer, inputAnswer);
}
}
一些提示
- 我看到您正在使用
==
来比较String
.从不这样做.请改用equals()
.请参见如何在Java中比较字符串?. - 我看到您有一个名为
Answer
的变量.根据Java命名约定,变量应以小写字母开头.请参阅Oracle网站上的代码约定.li> - 见上文;您可以将检查答案是否正确的责任转移到
Question
类,因为它包含答案字符串.请参见对象必须自行负责 - I see you are using
==
to compareString
s. Never ever do that. Useequals()
instead. See How do I compare strings in Java?. - I see you have a variable named
Answer
. According to the Java Naming Conventions, variables should start with a lowercase character. See Code Conventions at the Oracle website. - See above; you could transfer the responsibility of checking whether an answer is correct to the
Question
class, because it holds the answer string. See An Object Must be Responsible for Itself.
Some tips
这篇关于如何从数组中随机选择元素而不重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文