我正在开发一个功能类似于测验的程序。尽管我现在遇到问题,不允许用户在不输入猜测的情况下直接点击“Enter”并继续下一个问题。我正在尝试两种不同的方法,第一种方法是使用 try 和 catch 块,但我在理解它是如何工作的时候遇到了问题。我尝试查找 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# 书籍中找到答案。也许是可能是我只是不知道到底要找什么..