初学者代码,有些事情是不对的。 if和else if语句(C#)

时间:2015-10-02 07:57:53

标签: c# if-statement

我正在学习如何编程,所以请保持愉快。 :)

运行代码时出现此错误:

  

发生了'System.FormatException'类型的未处理异常   mscorlib.dll其他信息:输入字符串不正确   格式。

当我输入“拧你,不要告诉我该做什么!”。当我删除代码的整个侮辱部分时,它的工作完美无瑕。我做错了什么?

namespace ConsoleApplication6 
{
    class Program
    {
        static void Main(string[] args)
        {
            int numero1 = 5; //Declaring first variable
            int numero2 = 5; //Declaring second variable

            Console.WriteLine ("What is the answer of " + numero1 + " x " + numero2); //Asking question to the user

            int answer = Convert.ToInt32(Console.ReadLine()); //Converting the "answer" to integral variable
            string insult = Console.ReadLine(); //The user enter his insult          

            if (answer == 25) //If the answer is 25
            {
                Console.WriteLine("Good answer!"); //This message appears            
            }
            else if (insult == "screw you, don't tell me what to do!") //If the user insult me
            {
                Console.WriteLine("Wow buddy, gotta check that language!"); //The user receives this message              
            }
            else
            {
                Console.WriteLine("Dude...what?"); //If the user write anything else, he gets this message
            }
            Console.ReadKey();
        }
    } 
}

2 个答案:

答案 0 :(得分:1)

这样做:

        int numero1 = 5; //Declaring first variable
        int numero2 = 5; //Declaring second variable

        Console.WriteLine ("What is the answer of " + numero1 + " x " + numero2); //Asking question to the user

        string answer = Console.ReadLine(); //Converting the "answer" to integral variable


        if (answer == "25") //If the answer is 25
        {
            Console.WriteLine("Good answer!"); //This message appears            
        }
        else if (answer == "screw you, don't tell me what to do!") //If the user insult me
        {
            Console.WriteLine("Wow buddy, gotta check that language!"); //The user receives this message              
        }
        else
        {
            Console.WriteLine("Dude...what?"); //If the user write anything else, he gets this message
        }
        Console.WriteLine("Press any key to close the application");
        Console.ReadKey();

这是一个简单的更改,可以让您的代码更容易理解。你已经"硬编码"结果如此,将25放在一个字符串中,不会使你的代码不那么好。

答案 1 :(得分:0)

如下所示使用int.TryParse,如果用户输入非整数值,程序将失败

Console.WriteLine ("What is the answer of " + numero1 + " x " + numero2);
string keyboardInput = Console.ReadLine();
int answer;
while (!int.TryParse(keyboardInput, out answer)) {
    Console.WriteLine("Invalid input, try again.");
    keyboardInput = Console.ReadLine();
}
// now read the insult
string insult = Console.ReadLine(); 

因为您需要两个输入,您需要在输入答案后单击输入,然后再次输入insult并按Enter键