2
\$\begingroup\$

I've used this code to make some inputs checks. On any failed check, I need to ask again for proper input. I used labels and goto to achieve this, which they seem to be disliked by programmers as a concept.

How could I achieve the same effect without labels/goto? I considered putting all this code in a function and calling itself from inside, but it repeated only once for some reason - didn't keep asking if kept getting wrong answers.

// 0 exits
var f float64
var n int
startGame := func() {
reception:
    fmt.Println()
    fmt.Print(`Give number (1-9): `)
    _, err := fmt.Scan(&f)

    // check letters or symbols
    if err != nil {
        fmt.Println("Letters or symbols not accepted")
        goto reception
    }

    // exit
    if f == 0 {
        os.Exit(0)
    }

    // check for integers only
    if f < 1 || f > 9 || f-math.Ceil(f) != 0 {
        fmt.Println("Only integer numbers between 1-9 are accepted")
        goto reception
    }

    n = int(f)
    // check for empty cells
    if myArray[n-1] == false {
        fmt.Println("Empty cell", n)
        goto reception
    }
}
\$\endgroup\$
1
\$\begingroup\$

for {} (for loop without condition) loops forever until break.

  1. Put the contents of the function in a for {}.
  2. Remove the label and replace goto reception with continue. This will cause the current iteration of the loop to end and execution will continue with another iteration, starting from the top of the block.
  3. Use break at the end to exit the for loop
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.