Skip to content

Commit 7d01ba7

Browse files
committed
bug fix of correct answer index
1 parent d952ae4 commit 7d01ba7

3 files changed

Lines changed: 20 additions & 13 deletions

File tree

java/spring_quiz/.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,9 @@
33

44
# Ignore Gradle build output directory
55
build
6+
7+
# log rolling files, lock file
8+
*.log.*
9+
answers.txt
10+
answers.txt.lck
11+

java/spring_quiz/.vscode/launch.json

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,12 +4,6 @@
44
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
55
"version": "0.2.0",
66
"configurations": [
7-
{
8-
"type": "java",
9-
"name": "Current File",
10-
"request": "launch",
11-
"mainClass": "${file}"
12-
},
137
{
148
"type": "java",
159
"name": "Application",
@@ -20,6 +14,12 @@
2014
"env": {
2115
"JAVA_TOOL_OPTIONS": "-Djava.util.logging.config.file=${workspaceFolder}/logging.properties"
2216
}
17+
},
18+
{
19+
"type": "java",
20+
"name": "Current File",
21+
"request": "launch",
22+
"mainClass": "${file}"
2323
}
2424
]
2525
}

java/spring_quiz/src/main/java/com/securefromscratch/quiz/model/QuestionAndAnswers.java

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -22,15 +22,20 @@ public record ShuffledAnswers(String[] options, int correctAnswerIdx) { }
2222
public ShuffledAnswers generateShuffledAnswers() {
2323
String[] possibleAnswers = Arrays.copyOf(m_wrongAnswerOptions, m_wrongAnswerOptions.length + 1);
2424
possibleAnswers[m_wrongAnswerOptions.length] = m_correctAnswer;
25-
int correctAnswerIdx = secureShuffle(possibleAnswers, m_wrongAnswerOptions.length);
26-
return new ShuffledAnswers(possibleAnswers, correctAnswerIdx);
25+
secureShuffle(possibleAnswers);
26+
for (int i = 0 ; i < possibleAnswers.length ; ++i) {
27+
if (possibleAnswers[i].equals(m_correctAnswer)) {
28+
return new ShuffledAnswers(possibleAnswers, i);
29+
}
30+
}
31+
return new ShuffledAnswers(possibleAnswers, 0); // should never be reached
2732
}
2833

2934
public boolean isCorrectAnswer(String a_answer) {
3035
return a_answer.equals(m_correctAnswer);
3136
}
3237

33-
private static int secureShuffle(String[] a_toShuffle, int a_correctAnswerIdx) {
38+
private static void secureShuffle(String[] a_toShuffle) {
3439
SecureRandom random = new SecureRandom();
3540
for (int i = a_toShuffle.length - 1; i > 0; --i) {
3641
int toSwapWith = random.nextInt(i + 1);
@@ -39,10 +44,6 @@ private static int secureShuffle(String[] a_toShuffle, int a_correctAnswerIdx) {
3944
String savedFirstVal = a_toShuffle[toSwapWith];
4045
a_toShuffle[toSwapWith] = a_toShuffle[i];
4146
a_toShuffle[i] = savedFirstVal;
42-
if (a_correctAnswerIdx == toSwapWith) {
43-
a_correctAnswerIdx = i;
44-
}
4547
}
46-
return a_correctAnswerIdx;
4748
}
4849
}

0 commit comments

Comments
 (0)