generated from github/codespaces-blank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquiz.go
75 lines (63 loc) · 1.71 KB
/
quiz.go
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
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
// Question struct represents a quiz question
type Question struct {
QuestionText string
Answer string
}
// Quiz struct holds a collection of questions and the user's score
type Quiz struct {
Questions []Question
Score int
}
// NewQuiz creates a new quiz with a set of questions
func NewQuiz() Quiz {
questions := []Question{
{"What is the capital of France?", "Paris"},
{"Which planet is known as the Red Planet?", "Mars"},
{"What is the largest mammal?", "Blue Whale"},
{"Who wrote 'Romeo and Juliet'?", "William Shakespeare"},
{"What is the currency of Japan?", "Yen"},
}
return Quiz{Questions: questions, Score: 0}
}
// RunQuiz presents the quiz questions and collects user answers
func (q *Quiz) RunQuiz() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Welcome to the Quiz!")
// Ask 5 questions
for i := 0; i < 5; i++ {
question := q.Questions[i]
fmt.Println(question.QuestionText)
userAnswer, _ := getUserAnswer("Your answer: ", reader)
// Check if the answer is correct
if strings.EqualFold(userAnswer, question.Answer) {
fmt.Println("Correct!")
fmt.Println()
// Increment the score
q.Score += 20
} else {
fmt.Printf("Incorrect. The correct answer is: %s\n\n", question.Answer)
}
}
// Print the total score out of 100
fmt.Printf("Quiz completed. Your total score: %d out of 100\n", q.Score)
}
// getUserInput gets user input from the console
func getUserAnswer(prompt string, reader *bufio.Reader) (string, error) {
fmt.Print(prompt)
input, err := reader.ReadString('\n')
if err != nil {
return "", err
}
return strings.TrimSpace(input), nil
}
func main() {
quiz := NewQuiz()
quiz.RunQuiz()
}