我是Golang的新手,在网上学习了一个关于使用命令行终端制作一个简单的测验应用程序的教程.然而,当我在我的机器上运行代码时,在第一个问题之后,其余的问题成对出现,它不再接受我对每个问题的回答.
示例屏幕截图:
程序的流程非常简单--
- 接受本地CSV文件中的输入问题
- 打印每个问题并接受用户输入的答案
- 维护正确答案的计数,并在最后显示它们.
CSV文件也很短-
70+22,92
63+67,130
91+72,163
74+61,135
81+6,87
以下是完整的程序-
package main
import (
"encoding/csv"
"flag"
"fmt"
"os"
"time"
)
func main() {
// 1. input the name of the file
fName := flag.String("f", "quiz.csv", "path of csv file")
// 2. set the duration of timer
timer := flag.Int("t", 30, "timer for the quiz")
flag.Parse()
// 3. pull the problems from the file (calling our problem puller)
problems, err := problemPuller(*fName)
// 4. handle the error
if err != nil {
exit(fmt.Sprintf("something went wrong: %s", err.Error()))
}
// 5. create a variable to count our correct answers
correctAns := 0
// 6. using the duration of the timer, we want to initialize the timer
tObj := time.NewTimer(time.Duration(*timer) * time.Second)
ansC := make(chan string)
// 7. loop through the problems, print the questions, we'll accept the answers
problemLoop:
for i, p := range problems {
var answer string
fmt.Printf("Problem %d: %s =", i+1, p.question)
go func() {
fmt.Scanf("%s", &answer)
ansC <- answer
}()
select {
case <- tObj.C:
fmt.Println()
break problemLoop
case iAns := <- ansC:
if iAns == p.answer {
correctAns++
}
if i == len(problems)-1 {
close(ansC)
}
}
}
// 8. calculate and print out the result
fmt.Printf("Your result is %d out of %d\n", correctAns, len(problems))
fmt.Printf("Press enter to exit")
<- ansC
}
func problemPuller(fileName string) ([]problem, error) {
// read all the problems from the quiz.csv
// 1. open the file
if fObj, err := os.Open(fileName); err == nil {
// 2. we will create new reader
csvR := csv.NewReader(fObj)
// 3. it will need to read the file
if cLines, err := csvR.ReadAll(); err == nil {
// 4. call the parseProblem function
return parseProblem(cLines), nil
} else {
return nil, fmt.Errorf("error in reading data in csv from %s file; %s", fileName, err.Error())
}
} else {
return nil, fmt.Errorf("error in opening the file %s file; %s", fileName, err.Error())
}
}
func parseProblem(lines [][]string) []problem {
// go over the lines and parse them based on the problem struct
r := make([] problem, len(lines))
for i := 0; i < len(lines); i++ {
r[i] = problem {
question: lines[i][0],
answer: lines[i][1],
}
}
return r
}
type problem struct {
question string
answer string
}
func exit(msg string) {
fmt.Println(msg)
os.Exit(1)
}
我试着判断了每一行代码,但我无法解决它.有人能指出我做错了什么吗?