【问题标题】:How to get multiple random values from an array?如何从数组中获取多个随机值?
【发布时间】:2017-12-29 02:44:14
【问题描述】:

我正在使用 java 开发我的第一个 android 项目。

我有一个问题课;

public class Question {
    private int id;
    private String questionText;
    private String answer;
    private TextView textQuestion;

    public Question(int id, String questionText, String answer,TextView textQuestion) {
        this.id = id;
        this.questionText = questionText;
        this.answer = answer;
        this.textQuestion= textQuestion;
    }
}

我将使用这个类创建数组并存储一些问题和答案。但我的问题是例如 id = 0 它将是字母“A”,我希望至少有 5 个关于字母“A”的问题”。

Question[] questions = new Question[24];
questions[0] = new Question(0, "Question","Answer",textView);

如果我这样做,我只能为 id = 0 和字母“A”存储一个问题。我该怎么办?

编辑:通过说“我想对字母“A”至少有 5 个问题。”我的意思是会有答案以“A”或B、C等开头的问题。示例5个问题的答案以“A”开头。其他所有字母都一样。我可以使用这个类来创建问题和答案每个 id 和 letter ,但我需要对一个 id 有多个问题。 喜欢 ;

questions[0] = new Question(0, "Question","answer which starts with a",textView);
questions[1] = new Question(1, "Question","answer which starts with b",textView);
questions[2] = new Question(2, "Question","answer which starts with c",textView);

【问题讨论】:

  • 我不确定,你想得到什么效果。你想填写你的问题数组吗?如果是,请使用类似for(int i=0;i<questions.lenght;i++) 的循环。而且我不明白,您为什么要尝试将TextView 存储在您的对象中。如果是 textView 值,使用textView.getText()
  • “字母“A”的5个问题”这是什么意思?这与问题标题“如何从数组中获取多个随机值?”有什么关系?您没有在问题正文中再次提及随机。
  • 抱歉解释不好。有些问题的答案将以“A”或 B、C 等开头。示例 5 问题的答案以“A”开头。其他字母相同。 textView 用于不同的东西,与问题无关。我可以使用这个类为每个 id 和字母创建问题和答案,但我需要为一个 id 有多个问题。
  • 您想在id=0 中保存五个问题?
  • 是的,类似的。每个字母(id)至少五个问题。

标签: java android arrays random


【解决方案1】:

你可以这样做

List<Question> list = new ArrayList<>();
for(Question q : questions) {
    String s = q.answer;
    if(s.charAt(0) == 'a') {
        list.add(q);
    }
}

接下来使用Random类,这里是一个例子。

get random value from ArrayList

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 2015-07-02
    • 2019-03-09
    • 1970-01-01
    • 2020-08-07
    • 1970-01-01
    相关资源
    最近更新 更多