【问题标题】:random order quiz ِDynamic随机顺序测验ِ动态
【发布时间】:2019-09-26 16:54:45
【问题描述】:

我希望我的程序提出随机问题并获得动态答案但它只提出随机问题并且我需要动态答案

Button btn_1,btn_2;
TextView text;
setContentView(R.layout.activity_main);
btn_1=findViewById(R.id.btn_1);
btn_2=findViewById(R.id.btn_2);
text=findViewById(R.id.text);

int min = 1;
int max = 3;

Random r = new Random();
int rand = r.nextInt(max - min + 1) + min;
String[]question={"What is Name Color Sky ?",
      "What is Name Color Night?",
        "What is Blood Color?"
};

String[]answer={"Blue ",
        "Black",
        "White",
        "Red",
        "Green"
        ,"Purple"

};
text.setText(question[rand]); }

Screen

【问题讨论】:

  • 不是创建Strings 的数组,而是创建一个对象数组,其中包含问题和答案字符串作为其成员。然后随机提问,给出答案后,从对象中检索答案。或者,为了“简单”,创建一个Pair,其中包含一个问题和答案。
  • 为了澄清,您希望提供的答案有所不同吗?你想保证其中一个是正确的答案吗?您希望答案显示为代码顶部定义的两个 Button 对象的文本吗?

标签: android random


【解决方案1】:

试试这个:

btn_1.setText(answer[r.nextInt(6)])
btn_2.setText(answer[r.nextInt(6)])

这将独立选择 2 种随机颜色。

编辑

为确保提供正确答案,您需要将正确答案存储在某处。我强烈建议创建一个 Question 类来存储问题的字符串和正确答案,但是您可以只使用答案数组来达到预期的效果,例如:

Button[] answerButtons = new Button[] {btn1, btn2};
int numButtons = 2;
String[] correctAnswers = new String[] {"Blue", "Black", "Red"}; // you have a space after blue, remove it
List<String> answersDisplayed = Arrays.asList(new String[numButtons]);
int indexOfCorrectAnswer = random.nextInt(numButtons);
answersDisplayed.set(indexOfCorrectAnswer, correctAnswers[rand]); // the number used to pick the question earlier
for (int i = 0; i < numButtons; i++){
    if (correctAnswers[rand] == null) {
        // rand was used to pick the question, so pick the answer that goes with it
        // pick a random answer that hasn't come up yet
        String incorrectAnswer = answer[random.nextInt(6)];
        while (answersDisplayed.contains(incorrectAnswer)){
            incorrectAnswer = answer[random.nextInt(6)];
        }
        answersDisplayed.set(i, incorrectAnswer);
    }
    answerButtons[i].setText(answersDisplayed.get(i));
}

这适用于任意数量的按钮

【讨论】:

  • 嗨,答案不应该要求澄清。为此,您可以通过 cmets 询问。
  • 我想要的是,当一个随机问题被问到时,答案是随机在按钮一或按钮二上,它必须在按钮一和按钮二之间。
  • @King_Tesla 我已经编辑了我的答案,以确保正确的答案在一个按钮上,而另一个答案不同
  • 我没有使用这个解决方案,你的代码在我脑海中闪现,我找到了解决方案谢谢
猜你喜欢
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-19
  • 2017-05-10
  • 2012-03-15
  • 1970-01-01
相关资源
最近更新 更多