所以我写了我的第一个代码,它是一个迷你游戏,在1-100之间产生一个随机数,然后你想猜它。我遇到了一个错误,如果我输入的输入不是整数,程序就会崩溃。我想要它做的是WriteLine("不是一个整数")并返回goto循环。我已经看过一些关于这个问题的文章,但没有一个帮助过我。这是代码(对不起,如果它可怕:p之前从未进行过编程):
class Program
{
static void Main(string[] args)
{
Start:
Random rnd = new Random();
int number = rnd.Next(1, 101);
int guess = 0;
Console.WriteLine("Im thinking of a number between 0-100, guess what that number is");
Loop:
int keyStroke = int.Parse(Console.ReadLine());
if (keyStroke > number)
{
Console.WriteLine("Too big");
guess++;
goto Loop;
}
if (keyStroke < number)
{
Console.WriteLine("Too small");
guess++;
goto Loop;
}
if (keyStroke == number) {
Console.WriteLine("Correct");
guess++;
Console.WriteLine("Number of guessess = {0}", guess.ToString());
}
decision:
Console.WriteLine("Want to play again? (y/n)");
ConsoleKeyInfo yesno = Console.ReadKey();
if (yesno.KeyChar == 'y')
{
Console.Clear();
goto Start;
}
if (yesno.KeyChar == 'n')
{
}
else
{
Console.WriteLine("Incorrect input");
goto decision;
}
}
}