7

I'm making a program in Go for guessing a random number. I'm having issues with a for loop.

  1. I can't stop the for loop from continuously iterating.
  2. How do i break out of the loop once a condition is satisfied.

    for loop == true {
    
    //fmt.Println("read number", i, "/n")
    if i == ans {
        fmt.Println("well done")
    }
    if i != ans {
        fmt.Println("Nope")
        fmt.Scan(i)
    }
    
infiniteLearner
  • 3,555
  • 2
  • 23
  • 32
MartinF
  • 123
  • 1
  • 1
  • 4

1 Answers1

25

You need to break out of the loop:

for {
    fmt.Scan(i)
    if i == ans {
        fmt.Println("well done")
        break
    }
    if i != ans {
        fmt.Println("Nope")
    }
}
captncraig
  • 22,118
  • 17
  • 108
  • 151
  • Ok cool but its still wont let me loop properly. It goes into the loop then prints out nope if i dont enter a value any ideas? – MartinF Sep 28 '17 at 19:02
  • Then you're gonna need to be more specific. What is not as you expect it? – captncraig Sep 28 '17 at 19:04
  • 1
    Scan is probably not behaving as you expect it to. Read [the docs](https://golang.org/pkg/fmt/#Scan) and check your errors. – captncraig Sep 28 '17 at 19:11
  • 1
    and something like https://stackoverflow.com/a/40061275/121660 is usually a better way to read lines then Scan directly – captncraig Sep 28 '17 at 19:12
  • Solved it it was a combination of an issue with Scan and the loop i used continue to re loop when needed – MartinF Sep 29 '17 at 14:54
  • Add a `break` to the second `if` to stop the `for` loop continuously iterating? –  Apr 22 '20 at 02:26