如何在 C# 中给出无效输入后重新显示用户提示

本文关键字:新显示 显示 提示 用户 输入 无效 | 更新日期: 2023-09-27 18:37:12

我正在开发一个功能类似于测验的程序。尽管我现在遇到问题,不允许用户在不输入猜测的情况下简单地点击"Enter"并继续下一个问题。我正在尝试两种不同的方法,第一种方法是使用 try 和 catch 块,但我在理解它是如何工作的时遇到了问题。我尝试查找正确的语法来尝试和捕获块,并尝试包括中断并继续,尽管我会收到一条错误消息,内容为"没有要中断或继续的封闭循环"

public void Play()
    {
        DisplayWelcome();
        Console.WriteLine("First Question:");
        Console.WriteLine("---------------");
        Console.WriteLine(entertainmentquestions[0]);
        guess = Console.ReadLine();
        try
        {
            if (guess == entertainmentanswers[0])
            {
                Console.WriteLine("You got it right!");
                Console.WriteLine("Press 'Enter' when you are ready to see the next question");
                Console.ReadLine();
                Console.Clear();
            }
            else
            {
                Console.WriteLine("You got this one wrong! Better luck next one");
                Console.WriteLine("Press 'Enter' when you are ready to see the next question");
                Console.ReadLine();
                Console.Clear();
            }
            break;
        }
        catch 
        {
            Console.WriteLine("Incorrect input, please enter a valid answer");
            continue;
        }

我认为可以完成的第二种方法是通过 if 语句,但我不知道在用户点击输入显示为"无效"后如何重新提示用户

 public void Play()
    {
        DisplayWelcome();
        Console.WriteLine();
        Console.WriteLine("First Question:");
        Console.WriteLine("---------------");
        Console.WriteLine(hstryquestions[0]);
        guess = Console.ReadLine().ToUpper();
        if (guess != "")
        {
            if (guess == hstryanswers[0])
            {
                Console.WriteLine();
                Console.WriteLine("You got it right!");
                Console.WriteLine("Press 'Enter' when you are ready to see the next question");
                Console.ReadLine();
                Console.Clear();
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("You got this one wrong! Better luck next one");
                Console.WriteLine("Press 'Enter' when you are ready to see the next question");
                Console.ReadLine();
                Console.Clear();
            }
        }
        else if (guess == "")
        {
            Console.WriteLine("Please enter a valid answer");
            Console.ReadLine();
        }

任何帮助将不胜感激,我正在努力在网上和我拥有的 C# 书籍中找到这个问题的答案。也许可能是我只是不知道到底要寻找什么。

如何在 C# 中给出无效输入后重新显示用户提示

尝试使用循环!也许是一个做同时循环!

像这样:

do{
ask for input
get input
}while(input is not valid)

这种循环将重复获取用户输入,直到输入通过您定义的某些有效性测试。下面是一个关于 C# 中 do while 循环的教程:http://www.dotnetperls.com/do