Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "bufio"
- "fmt"
- "math/rand"
- "os"
- "strconv"
- "time"
- )
- func main() {
- const MIN int = 1
- const MAX int = 100
- // Init a new rand object
- r := rand.New(rand.NewSource(time.Now().UnixNano()))
- // Init the state of our program
- answer := r.Intn(MAX) + MIN
- guess := -1
- min := MIN
- max := MAX
- // Build a scanner object which receives data from standard input
- scanner := bufio.NewScanner(os.Stdin)
- // Main game loop
- OUTER_LOOP:
- for {
- // Receive user input
- INNER_LOOP:
- for {
- fmt.Print("Input a number between ", min, " and ", max, ": ")
- for scanner.Scan() {
- input := scanner.Text()
- n, err := strconv.ParseInt(input, 10, 0) // n is int64
- // Convert the number from int64 to int
- num := int(n)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Invalid number: %s\n", input)
- break
- } else if num < min || num > max {
- fmt.Fprintf(os.Stderr, "Number out of range: %d\n", num)
- break
- } else {
- guess = num
- break INNER_LOOP
- }
- }
- }
- // Check our guess is correct
- if guess > answer {
- fmt.Println("Too large")
- max = guess
- } else if guess < answer {
- fmt.Println("Too small")
- min = guess
- } else {
- fmt.Println("You guess right")
- break OUTER_LOOP
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement