我正在开发一个像测验一样运作的程序。虽然我现在遇到问题但不允许用户简单地点击“输入”#39;没有输入猜测并继续下一个问题。 我正在尝试两种不同的方法,第一种方法是使用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#书中的答案。也许可能是因为我不知道到底要找什么......
答案 0 :(得分:1)
尝试使用循环!也许是一个do-while循环!
这样的事情:
do{
ask for input
get input
}while(input is not valid)
这种循环会反复获取用户输入,直到输入通过您定义的某些有效性测试。这是关于在C#中执行while循环的教程:http://www.dotnetperls.com/do