How do I keep Scan from reading all characters from a user input in GO?

Viewed 23

I am currently trying to validate user input for a random team generator. The user inputs the number of team members per team and the program breaks up the list of names into teams. If I put in a string it outputs an error message for each character in the string. I want it to output just one error message even if I type several characters.

//Dan Bell
//Random team generator

package main

import (
    "bufio"
    "fmt"
    "log"
    "math/rand"
    "os"
    "strings"
    "time"
)

func main() {

    var my_slice []string

    // open the names.txt file contained in the same directory
    f, err := os.Open("names.txt")

    if err != nil {
        log.Fatal(err)
    }

    defer f.Close()
    //scan the contents of the .txt file into a slice
    scanner := bufio.NewScanner(f)

    for scanner.Scan() {

        my_slice = append(my_slice, scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
    //shuffle the slice so that the groups are random each time
    rand.Seed(time.Now().UnixNano())
    rand.Shuffle(len(my_slice), func(i, j int) { my_slice[i], my_slice[j] = my_slice[j], my_slice[i] })

    fmt.Println("\nWelcome to our team generator" + "\n\n\n" + "How big should the teams be?")

    var teamSize int

    //put the user input into the teamSize variable
    //validate input 
    for {
        _, err := fmt.Scan(&teamSize)
        if err != nil {
            fmt.Println("\nEnter a valid number")
        } else {
            break
        }

    }
    // fmt.Scanln(&teamSize)

    var divided [][]string
    //chop the slice into chunks sized using the teamSize entered by a user
    for i := 0; i < len(my_slice); i += teamSize {
        end := i + teamSize

        if end > len(my_slice) {
            end = len(my_slice)
        }

        divided = append(divided, my_slice[i:end])
    }
    //print each group
    for i := 0; i < len(divided); i++ {
        fmt.Println("\nGroup " + fmt.Sprint(i+1) + "\n" + strings.Join(divided[i], ", "))
    }

}

0 Answers
Related