[英]Using “if” to give custom error messages in C#
I have just started to learn how to programm using c# I am usin visual studio 2013 and I dont know the version of c# 我刚刚开始学习如何使用C#编程我在Visual Studio 2013中使用,但我不知道C#的版本
Here I have a code to paint the background of command application 这里我有一段代码来描绘命令应用程序的背景
for (; ; )
{
Console.WriteLine("Give a number to select a colour between 0-15? ");
ConsoleColor renk;
renk = (ConsoleColor)Convert.ToInt32(Console.ReadLine());
Console.BackgroundColor = renk;
Console.Clear();
}
The thing is, when user gives any color, it paints the background, and loops to the start, so the user can type new one(number) 问题是,当用户提供任何颜色时,它会绘制背景,并循环到起点,因此用户可以键入新的数字(数字)
BUT 但
When the user just dont type a number and press enter, it just gives an error and crashes. 当用户不输入数字并按Enter时,它只会给出错误并崩溃。 How can I show a message and loop it to the start, when the user don't give a number?
当用户不输入号码时,如何显示消息并将其循环播放?
I've tried this; 我已经尝试过了
if(renk)
{
Console.WriteLine("My error message!");
}
But I don't know how to define "if "renk" is not defined" Like, if I was trying to work this code when "renk" is < 5 then I'd write; 但是我不知道如何定义“如果未定义“ renk””。例如,如果我试图在“ renk”小于5时使用此代码,那么我会写;
if(renk<5)
{
Console.WriteLine("My error message!");
}
else
{
bla bla bla
}
Use int.TryParse for checking string number inputs. 使用int.TryParse检查字符串输入。
You will enter the "if" only if a number was inputted(and you will have the number in the num var). 仅当输入数字时,您才输入“ if”(并且该数字将在num var中)。
for (; ; )
{
Console.WriteLine("Give a number to select a colour between 0-15? ");
ConsoleColor renk;
int num;
string strNum = Console.ReadLine();
if(int.TryParse(strNum, out num) && (num >= 0 && num <= 15))
{
Console.BackgroundColor = (ConsoleColor)num;
Console.Clear();
}
else
{
Console.WriteLine("Error");
}
}
int inputNumber = 0;
for (; ; )
{
Console.WriteLine("Give a number to select a colour between 0-15? ");
ConsoleColor renk;
if(int.TryParse(Console.ReadLine(),out inputNumber) && (inputNumber>=0 && inputNumber<=15))
{
renk = (ConsoleColor)Convert.ToInt32(inputNumber);
Console.BackgroundColor = renk;
Console.Clear();
}
else
{
Console.WriteLine("No Input Received! Quitting!");
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.