In this code, I am trying to repeat the if-statement again if the condition is false or default but the loop stops at the default.
- If I write
Scanln
inside the loop then it does not let me input the data - If I write
Scanln
outside the loop then it does not repeat the loop.
How to repeat the loop again and again until I enter the correct choice?
package main
import "fmt"
func main() {
var choice int
fmt.Printf("Enter your choice: ")
_, err := fmt.Scanln(&choice)
if err != nil {
fmt.Println("Letters or symbols not accepted")
}
for choice == 1 || choice == 2 {
switch choice {
case 1:
fmt.Println("1 is selected")
case 2:
fmt.Println("2 is selected")
default:
fmt.Printf("Please enter the correct choice: ")
}
}
}
CodePudding user response:
Below script will get your work done.
package main
import "fmt"
func main() {
var choice int
for choice != 1 || choice != 2 {
fmt.Printf("Enter your choice: ")
_, err := fmt.Scanln(&choice)
if err != nil {
fmt.Println("Letters or symbols not accepted")
}
switch choice {
case 1:
fmt.Println("1 is selected")
case 2:
fmt.Println("2 is selected")
default:
fmt.Printf("Please enter the correct choice: ")
}
}
}