我目前正在开发一个用 java 创建测验演示的项目。然而,当我随机排列问题答案选项时,正确答案索引被混淆了,我无法修复它。请帮忙。谢谢你
随机播放方法: 私人字符串[] shuffleOptions(字符串[]选项,int答案){ 随机运行 = new Random();
// Answer value before shuffling
String answerValue = options[answer];
// Shuffle options randomly
for (int i = options.length - 1; i > 0; i--) {
int index = ran.nextInt(i + 1);
String temp = options[index];
options[index] = options[i];
options[i] = temp;
}
// Find the new correct answer index after shuffling
for (int i = 0; i < options.length; i++) {
if (options[i].equals(answerValue)) {
answerTemp = i;
}
}
return options;
}
使用(在所有问题的 for 循环中):
public void giveQuiz() {
Scanner userInput = new Scanner(System.in);
int userAnswer = 0;
for (int i = 0; i < size; i++) {
Question currentQuestion = questions[i];
System.out.println("Question " + (i + 1) + ") : " + currentQuestion.getQuestion());
String[] shuffledOptions = shuffleOptions(currentQuestion.getOptions(), currentQuestion.getAnswer());
currentQuestion.setAnswer(answerTemp); // Sets correct answer value to index
for (int x = 0; x < shuffledOptions.length; x++) { // Prints shuffled options
System.out.println("(" + (x + 1) + ") " + shuffledOptions[x]);
}
System.out.println("\n Type Answer (1-4): ");
userAnswer = userInput.nextInt();
if (userAnswer == currentQuestion.getAnswer()) { //Checks for correct answer
System.out.println("\nCORRECT ANSWER");
score++;
}
else {
System.out.println("\nWRONG ANSWER");
}
}
System.out.println(finalScore());
userInput.close();
} //end of giveQuiz
输入正确答案的数字 输出不正确
根据您的代码,
answerTemp
是一个全局变量。我认为全局变量的意外修改就是原因。
你能发布完整的代码以便我找出错误的原因吗?