英文:
How to repeat the conditional statement until the choice is correct?
问题
在这段代码中,我试图在条件为假或默认时再次重复 if 语句,但循环在默认情况下停止。
- 如果我在循环内部写入
Scanln
,它不会让我输入数据。 - 如果我在循环外部写入
Scanln
,它不会重复执行循环。
如何重复执行循环,直到我输入正确的选择?
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: ")
}
}
}
英文:
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: ")
}
}
}
答案1
得分: 1
以下脚本将完成您的工作。
package main
import "fmt"
func main() {
var choice int
for choice != 1 || choice != 2 {
fmt.Printf("请输入您的选择:")
_, err := fmt.Scanln(&choice)
if err != nil {
fmt.Println("不接受字母或符号")
}
switch choice {
case 1:
fmt.Println("选择了1")
case 2:
fmt.Println("选择了2")
default:
fmt.Printf("请输入正确的选择:")
}
}
}
希望对您有帮助!
英文:
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: ")
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论