【问题标题】:Making JRadioButton random使 JRadioButton 随机
【发布时间】:2016-08-18 20:13:23
【问题描述】:

我的数据来自像这样对我的单选按钮的查询:

radio1.setText(Question.get(i).getChoiceOne()) // assign ist choice to ist radio button
radio2.setText(Question.get(i).getChoiceTwo()) // assign second choice to second radio
radio3.setText(Question.get(i).getcorrectchoice()) // assign correct choice to third radio button

在这种情况下,每次将正确答案分配给第三个单选按钮,这使得测验可预测。我可以以某种方式做到这一点,其中正确的选择有时分配给第一个单选,有时分配给第二个等等?

【问题讨论】:

  • @LukasRotter 或只是 Collections.shuffle() 在该列表中。
  • @Selim Wow...不敢相信我以前从未听说过这种方法,谢谢!

标签: java swing random jradiobutton


【解决方案1】:

您可以执行以下操作:

String one = Question.get(i).getChoiceOne();
String two = Question.get(i).getChoiceTwo();
String three = Question.get(i).getcorrectchoice();

// construct list from questions.
List<String> choices = Arrays.asList(one, two, three);

// give random order to list
Collections.shuffle(choices);

// set radio button texts
radio1.setText(choices.get(0));
radio2.setText(choices.get(1));
radio3.setText(choices.get(2));

【讨论】:

  • @Seleim 非常感谢。但是假设我想计算点数,那么我怎样才能找出正确的选择呢?
  • if (Question.get(i).getcorrectchoice().equals(actionEvent.getSource().getText())) {...}
【解决方案2】:
      int i = (Math.random() * 1000)%3;// generate a values between 0-2
      String[] answers = new String[3];
      answers[i] = Question.get(i).getcorrectchoice();// i is the index of right answer

      // insert the 2 other answers, what ever i you chose (i+1)%3 will put them in the remaining 2 places  
      answer[(i+1)%3] = Question.get(i).getfirstchoice(); 
      answer[(i+1)%3] = Question.get(i).getsecondchoice();
      i = (i+1)%3;// the original value of i
      // insert radios
      radio1.setText(answers[0]);
      radio2.setText(answers[1]);
      radio3.setText(answers[2]);

      //  get the right answer; get the text of the selected radio 
      if(textOfselectedRadio.quals(answers[i])){
      // correct 
      }

【讨论】:

  • @Whynot 谢谢,但我已经使用了 Collections.shuffle(choices);方法,它的工作原理。现在在这里我不知道如何指出正确答案并增加分数,因为答案可以在三个单选按钮之一中? radio1.setText(choices.get(0)); radio2.setText(choices.get(1)); radio3.setText(choices.get(2));
  • 你应该阅读并理解代码,你所说的要么在我的代码中,要么在 Selim 的代码中。为分数声明一个应该包含它的静态变量;每次你得到一个正确的答案分数都会增加。最后,如果其中一个答案解决了您的问题,请不要忘记验证它=]
  • 我知道如果选择了正确的选项,变量应该增加,但我的问题是如何在这段代码中找出正确的选项?字符串一 = Question.get(i).getChoiceOne();字符串二 = Question.get(i).getChoiceTwo();字符串三 = Question.get(i).getCorrectChoice(); List 选择 = Arrays.asList(一、二、三); Collections.shuffle(选择); c1.setText(choices.get(0).toString()); c2.setText(choices.get(1).toString()); c3.setText(choices.get(2).toString());
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-09
  • 1970-01-01
相关资源
最近更新 更多