gpt4 book ai didi

java - 如何才能使随机不重复呢?

转载 作者:行者123 更新时间:2023-12-01 19:35:05 25 4
gpt4 key购买 nike

我创建了一个随机选择显示的字符串列表,因此我想让它不会重复。我怎样才能做到这一点。

public class qustionsActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);

final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
final String randomQuestions = questions[new Random().nextInt(questions.length)];

final TextView theQuestion = findViewById(R.id.theQustion);

theQuestion.setText(randomQuestions);

Button nextQuestion = findViewById(R.id.nextQuestion);

nextQuestion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

String randomQuestions = questions[new Random().nextInt(questions.length)];
theQuestion.setText(randomQuestions);

}
});
}

我有两个“randomQuestions”字符串的原因是因为我希望您进入 Activity 后立即显示一个问题,并且单击按钮时它将随机生成一个新字符串。

最佳答案

您可以随机打乱问题并按顺序回答下一个(随机)问题,而不是每次都随机选择。

private final List<String> randomQuestions;
private int questionI;

// Cycling endlessly
private String nextQuestion() {
String question = randomQuestions.get(questionI);
++questionI;
if (questionI > randomQuestions.size()) {
questionI = 0;
}
}

// Once through the list:
private String nextQuestion() {
return randomQuestions.remove(0); // Always take the first, removing it.
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qustions);

final String[] questions = getResources().getStringArray(R.array.coupleQuestions);
randomQuestions = Collections.shuffle(Arrays.asList(questions));

关于java - 如何才能使随机不重复呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58113244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com