-2

我在这段代码中面临的问题是循环的第一次迭代很好,但是在第二次迭代中,当我按下 y 时,程序会出错。错误 = 输入字符串的格式不正确。

错误行 = my = int.Parse(Console.ReadLine());

static void Main(string[] args)
{
    int a, my;
    char again = 'y';
    while ((again == 'y' || again=='Y'))
    {
        Console.Write("Enter the value for your number = ");
        my = int.Parse(Console.ReadLine());
        Random b = new Random();
        a = b.Next(1, 6);
        if (a == my)
        {
            Console.WriteLine("Congratulations");
        }
        else
        {
            Console.WriteLine("you Lost");
            Console.WriteLine("My no is {0}.", a);
        }
        Console.Write("Again? Then press 'y' or 'Y' = ");
        again = (char)Console.Read();
    }
    Console.ReadLine();
}
4

2 回答 2

2

改变

again = (char)Console.Read();

again = (char)Console.ReadLine().First();

Console.Read从标准输入流中读取下一个字符。要继续,请按一个键(在这种情况下为“y”)并按“输入”。这意味着您输入 2 个字符并读取 1。 next 读取哪个字符Console.Readline。所以,你永远不会在这一行得到实际的字符串

my = int.Parse(Console.ReadLine());

相反,你得到了你以前没有读过的角色。而这个不能解析为整数。

于 2013-10-20T20:08:37.110 回答
0

如果您进入Input string was not in a correct formata Int32.Parse,请尝试将其替换为 aInt32.TryParse

Int32.TryParse(Console.ReadLine(), out my);
于 2013-10-20T20:10:14.143 回答