以随机顺序显示多项选择题

时间:2017-05-25 12:31:21

标签: java random eclipse-plugin

以下是按顺序显示多项选择题的代码。 它显示一个问题,得到答案并检查是否正确。

  public static void Rap() {
  Scanner input = new Scanner(System.in);
  int correct = 0;

  //1
  System.out.println("Complete the lyrics(hint travis scott): 'dont you open up that...  \n A.can of coke \n B.window \n C. back door \n D. water bottle ");
  String x = input.next();
  if (x.equalsIgnoreCase("b")) {
   System.out.println("Correct");
   correct++;
  }
  if (x.equalsIgnoreCase("a")) {
   System.out.println("incorrect");
  }
  if (x.equalsIgnoreCase("c")) {
   System.out.println("incorrect");
  }
  if (x.equalsIgnoreCase("d")) {
   System.out.println("incorrect");
  }
  //Same for other questions

  System.out.println("You got " + correct++ + "/15 good or bad job i guess");   

请建议如何随机化此流程?

1 个答案:

答案 0 :(得分:1)

看起来你是编程的初学者,太棒了!

从您的代码中我理解的是:您向用户显示了n个问题,并且您希望保留正确答案的数量。

从算法,

for every question in n questions,
    display one question
    read the input
    if input is correct, increment the correct count
    display correct/incorrect
    go to next question

<强>解决方案: 这个答案可能看起来很复杂,但相信我,你会在这里学到很多东西。

首先,创建一个类来存储您的问题和正确的答案选项。

class Question {
    /*Read about private access specifier and getter/setter methods*/
    String question;
    String correctOption;
    public Question(String question, String correctOption) {
        this.question = question;
        this.correctOption = correctOption;
    }
}

其次,创建这些问题对象的列表(了解数组http://www.c-sharpcorner.com/UploadFile/0c1bb2/login-page-in-Asp-Net-C-Sharp-web-application-using-stored-proce/和列表here

List<Question> allQuestions = new ArrayList<Question>();
allQuestions.add(new Question("YOUR_QUESTION", "CORRECT_OPTION"));
/*Example:*/
allQuestions.add(new Question("Complete the lyrics(hint travis scott): 'dont you open up that... \n A.can of coke \n B.window \n C. back door \n D. water bottle", "b"));
/* TODO do this for all the 15 questions*/

第三次,随机播放Question中的allQuestions个对象     import java.util.Collections

Collections.shuffle(allQuestions);

最后,请按照上述算法进行操作:

//TODO prepare allQuestions as explained above
for (int i=0; i < allQuestions.size(); i++) {
    Question curQuest = allQuestions.get(i);
    System.out.println(curQuest.question)
    String ans = input.next();
    if(ans.equalsIgnoreCase(curQuest.correctOption)) {
        System.out.println("Correct");
        correct++;
    } else {
        System.out.println("incorrect");
    }
}
System.out.println("You got "+ correct++ +"/15 good or bad job i guess");
相关问题