Hello everyone, I’m new to programming and to Go. I’m trying to build a small program on my own while reading Head First Go book, and I’ve come across a problem. Please help.
The following is sample code to my original code. I want to repeat the last else block until the user has typed in either y or n. How do I implement this?
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
fmt.Println("Wage Calculator")
repeat := true
for repeat {
fmt.Println("get data from user")
fmt.Println("calculate wage")
fmt.Println("display wage")
fmt.Println("Do you want to stop now? (Type y for yes or n for no)")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
}
input = strings.TrimSpace(input)
// Validating user input
if input == "y" {
repeat = false
} else if input == "n" {
repeat = true
} else {
fmt.Println("Please type either y or n.")
}
}
}
To repeatedly ask for the correct input, you need a second loop that is nested inside the first one. This inner loop shall read and validate the user’s input repeatedly.
If the user types y, the inner loop can end and let the outer loop repeat.
If the user types n, the inner loop can end and let the outer loop end.
If the user types something else, the inner loop asks the user to just f*ing press y or n, thank you very much, and repeats.
func main() {
fmt.Println("Wage Calculator")
repeat := true
badinput := false
for repeat {
if !badinput {
fmt.Println("get data from user")
fmt.Println("calculate wage")
fmt.Println("display wage")
fmt.Println("Do you want to stop now? (Type y for yes or n for no)")
} else {
fmt.Println("Please type either y or n.")
}
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
}
input = strings.TrimSpace(input)
// Validating user input
if input == "y" {
repeat = false
} else if input == "n" {
badinput = false
} else {
badinput = true
}
}
}