How to loop a line in else statement until condition is met?

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.")
		}
	}
}

Thanks for taking the time to read my post.

Hi @Bangali_Babu,

Welcome to the Go Forum!

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.

1 Like

On second thought, the inner loop can of course be a bit more polite.

At least for the first few unsuccessful iterations. Then the loop can gradually start making a rumpus until the user gets it.

1 Like

Hi,

Or something like that :

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
		}
	}
}