请更正我的代码。请告诉我,这段代码发生了什么

时间:2013-10-20 19:59:54

标签: c#

问题,我在这段代码中面临的是循环的第一次迭代是好的,但是当我按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();
}

2 个答案:

答案 0 :(得分:2)

更改

again = (char)Console.Read();

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

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

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

而是你得到了之前没有读过的角色。而这个不能解析为整数。

答案 1 :(得分:0)

如果Input string was not in a correct format中有Int32.Parse,请尝试将其替换为Int32.TryParse

Int32.TryParse(Console.ReadLine(), out my);