以随机顺序显示多项选择题 [英] Display multiple choice questions in a random order
问题描述
下面是依次显示多项选择题的代码。
它显示一个问题,获取答案并检查其正确性。
Below is the code that displays multiple choice questions sequentially. It displays a question, gets the answer and checks for correctness.
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");
请建议如何随机化此流程?
Please suggest how to randomize this flow?
推荐答案
看来您是编程的初学者,太好了!
It looks like you are a beginner to programming, that's great!
根据您的代码,我了解到:向用户显示的问题数量为 n
,并且您希望保留正确答案的数量。
From your code what I understand is: you have n
number of questions displayed to the user and you want to keep count of correct answers.
从算法上讲,
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
解决方案:
这个答案可能看起来很复杂,但是请相信我,您会在这里学到很多东西。
Solution: This answer might look complex, but trust me, you will learn a lot of things here.
首先,创建一个课程来存储您的问题并纠正答案的选项。
First, create a class to store your question and correct answer's option.
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;
}
}
第二,创建一个这些问题对象的列表(在数组此处中了解并列出此处)
Secondly, create a list of these question objects (Read about array here and Lists 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*/
第三,在 allQuestions
import java.util.Collections
Thirdly, shuffle the Question
objects in the 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");
这篇关于以随机顺序显示多项选择题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!