-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuizApp.java
More file actions
84 lines (71 loc) · 2.63 KB
/
Copy pathQuizApp.java
File metadata and controls
84 lines (71 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
class Question {
String question;
String[] options;
int correctAnswer;
Question(String question, String[] options, int correctAnswer) {
this.question = question;
this.options = options;
this.correctAnswer = correctAnswer;
}
}
public class QuizApp {
private static final int TIME_LIMIT = 10; // seconds
private static ArrayList<Question> quizQuestions = new ArrayList<>();
private static int score = 0;
private static int currentQuestionIndex = 0;
private static Timer timer = new Timer();
private static boolean timeUp = false;
private static Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
// Add quiz questions
quizQuestions.add(new Question("What is the capital of France?", new String[]{"Berlin", "Madrid", "Paris", "Lisbon"}, 2));
quizQuestions.add(new Question("Which planet is known as the Red Planet?", new String[]{"Earth", "Mars", "Jupiter", "Saturn"}, 1));
// Start the quiz
for (currentQuestionIndex = 0; currentQuestionIndex < quizQuestions.size(); currentQuestionIndex++) {
askQuestion(quizQuestions.get(currentQuestionIndex));
}
// Display the result
displayResult();
}
private static void askQuestion(Question question) {
System.out.println(question.question);
for (int i = 0; i < question.options.length; i++) {
System.out.println((i + 1) + ". " + question.options[i]);
}
timeUp = false;
timer.schedule(new TimerTask() {
@Override
public void run() {
timeUp = true;
}
}, TIME_LIMIT * 1000);
int answer = getAnswer();
timer.cancel();
timer = new Timer(); // reset timer
if (answer == question.correctAnswer + 1) {
score++;
}
}
private static int getAnswer() {
int answer = -1;
while (!timeUp && (answer < 1 || answer > 4)) {
if (scanner.hasNextInt()) {
answer = scanner.nextInt();
} else {
scanner.next(); // clear invalid input
}
}
if (timeUp) {
System.out.println("Time's up!");
}
return answer;
}
private static void displayResult() {
System.out.println("Quiz Over!");
System.out.println("Your Score: " + score + "/" + quizQuestions.size());
}
}