如何使程序等待进一步的输入?

huangapple go评论93阅读模式
英文:

How to make program wait for further input?

问题

如果你想让程序在等待其他问题的答案后再继续执行,你可以按照以下方式修改代码:

package main

import (
	"bufio"
	"fmt"
	"os"
	"time"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Printf("How long did the christians walk for the crusade? :")
	scanner.Scan()
	input := scanner.Text()

	if input == "3 years" {
		fmt.Println("Correct!")
	} else {
		fmt.Println("Incorrect.")
		return // 添加 return 语句,结束程序
	}

	fmt.Printf("How many of the crusades were won by christians? :")
	scanner.Scan()
	input = scanner.Text()

	if input == "1" {
		fmt.Println("Correct!")
	} else {
		fmt.Println("Incorrect.")
		return // 添加 return 语句,结束程序
	}

	fmt.Printf("Who started the crusades? :")
	scanner.Scan()
	input = scanner.Text()

	if input == "the pope" {
		fmt.Println("Correct!")
	} else {
		fmt.Println("Incorrect.")
		return // 添加 return 语句,结束程序
	}

	fmt.Printf("Thank you for playing!")
	time.Sleep(2 * time.Hour)
}

通过在每个问题后添加 return 语句,如果答案不正确,程序将会提前结束。这样就可以等待用户输入每个问题的答案后再继续执行。

英文:

If I run the below program and enter an answer (e.g. "3 years") the program completes without waiting for any further input e.g.:

How long did the christians walk for the crusade? :3 years
Correct!
How many of the crusades were won by christians? :Incorrect.
Who started the crusades? :Incorrect.
Thank you for playing!

How can I make it wait for answers to the other questions?

package main

import (
	"bufio"
	"fmt"
	"os"
	"time"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	fmt.Printf("How long did the christians walk for the crusade? :")
	scanner.Scan()
	input := scanner.Text()

	if input == "3 years" {
		fmt.Println("Correct!")
	} else {
		fmt.Println("Incorrect.")
	}

	fmt.Printf("How many of the crusades were won by christians? :")

	if input == "1" {
		fmt.Println("Correct!")
	} else {
		fmt.Println("Incorrect.")
	}

	fmt.Printf("Who started the crusades? :")

	if input == "the pope" {
		fmt.Println("Correct!")
	} else {
		fmt.Println("Incorrect.")
	}

	fmt.Printf("Thank you for playing!")
	time.Sleep(2 * time.Hour)
}

答案1

得分: 1

以上代码将接受一行输入,并将结果存储在变量input中。

所以当你的程序运行时,它会问第一个问题并等待答案;假设我回答“1天”,那么input == "1天"。在此之后,input的值不会改变-你正在将用户输入的第一个值与多个答案进行比较,即"1天" == "3年""1天" == "教皇"

如果你想接受额外的行,你需要重复调用scanner.Scan(),例如:

scanner.Scan()
input := scanner.Text()

if input == "3年" {
    fmt.Println("正确!")
} else {
    fmt.Println("错误。")
}

fmt.Printf("十字军中有多少次是基督徒赢得了胜利?:")
scanner.Scan() // 从scanner获取下一个答案
input = scanner.Text()

if input == "1" {
    fmt.Println("正确!")
} else {
    fmt.Println("错误。")
}

请注意,你可以通过使用一个函数来简化这个过程:

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    s := bufio.NewScanner(os.Stdin)

    askQuestion(s, "基督徒为了十字军而行走了多久?:", "3年")
    askQuestion(s, "十字军中有多少次是基督徒赢得了胜利?:", "1")
    askQuestion(s, "谁发起了十字军?:", "教皇")

    fmt.Printf("谢谢参与!")
}

func askQuestion(s *bufio.Scanner, question string, answer string) {
    fmt.Print(question)
    if !s.Scan() {
        panic(fmt.Sprintf("扫描失败:%s", s.Err()))
    }
    if s.Text() == answer {
        fmt.Println("正确!")
    } else {
        fmt.Println("错误。")
    }
}
英文:
scanner.Scan()
input := scanner.Text()

The above will accept a single line of input and store the result in the variable input.

So when your program runs it asks the first question and waits for an answer; lets say I answer with "1 day" then input == "1 day". The value of Input is not changed after that point - you are comparing the first value the user enters against multiple answers i.e. "1 day" == "3 years" and "1 day" == "the pope".

If you want to accept additional lines you will need to repeat the call e.g.

scanner.Scan()
input := scanner.Text()

if input == "3 years" {
	fmt.Println("Correct!")
} else {
	fmt.Println("Incorrect.")
}

fmt.Printf("How many of the crusades were won by christians? :")
scanner.Scan() // Get next answer from scanner
input = scanner.Text()

if input == "1" {
	fmt.Println("Correct!")
} else {
	fmt.Println("Incorrect.")
}

Note that you can simplify this considerably by using a function:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	s := bufio.NewScanner(os.Stdin)

	askQuestion(s, "How long did the christians walk for the crusade? :", "3 years")
	askQuestion(s, "How many of the crusades were won by christians? :", "1")
	askQuestion(s, "Who started the crusades? :", "the pope")

	fmt.Printf("Thank you for playing!")
}

func askQuestion(s *bufio.Scanner, question string, answer string) {
	fmt.Print(question)
	if !s.Scan() {
		panic(fmt.Sprintf("scan failed: %s", s.Err()))
	}
	if s.Text() == answer {
		fmt.Println("Correct!")
	} else {
		fmt.Println("Incorrect.")
	}
}

huangapple
  • 本文由 发表于 2022年2月13日 09:20:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/71097185.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定