while loops, an example



You want user to choose between 1 or 2. If they give you something else, the program loops asking them to choose between 1 or 2.

package main
import "fmt"

func main() {
    var choice int
    for choice != 1 && choice !=2 {
        fmt.Println("Pick a number between 1 or 2")
        fmt.Scanf("%d", &choice)
    }
    fmt.Printf("You chose %d\n", choice)
}

UPDATE:
Here's another one. Let's say user just finished a game. Ask to play again--yes or no?

package main
import "fmt"

func main() {
    choice := "y"
    for choice == "y" {
        fmt.Println("Play again? y or n")
        fmt.Scanf("%s", &choice)
    }
    fmt.Println("Bye!")
}

No comments:

Post a Comment