初学者写代码,有些地方不太对.If和else If语句(c#)

本文关键字:If else 语句 方不太 代码 初学者 | 更新日期: 2023-09-27 18:15:43

我正在学习如何编程,所以请很好。:)

我有这个错误运行代码:

类型为"System"的未处理异常。FormatException'发生在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 "answerswer" 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();
        }
    } 
}

初学者写代码,有些地方不太对.If和else If语句(c#)

这样做:

        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 "answerswer" 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,在一个字符串中,不会使你的代码不太好。

如下所示使用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(); 

由于您需要两个输入,因此您需要在输入答案后单击enter,然后您可以再次键入侮辱并按enter