[英]Using “if” to give custom error messages in C#
我刚刚开始学习如何使用C#编程我在Visual Studio 2013中使用,但我不知道C#的版本
这里我有一段代码来描绘命令应用程序的背景
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();
}
问题是,当用户提供任何颜色时,它会绘制背景,并循环到起点,因此用户可以键入新的数字(数字)
但
当用户不输入数字并按Enter时,它只会给出错误并崩溃。 当用户不输入号码时,如何显示消息并将其循环播放?
我已经尝试过了
if(renk)
{
Console.WriteLine("My error message!");
}
但是我不知道如何定义“如果未定义“ renk””。例如,如果我试图在“ renk”小于5时使用此代码,那么我会写;
if(renk<5)
{
Console.WriteLine("My error message!");
}
else
{
bla bla bla
}
使用int.TryParse检查字符串输入。
仅当输入数字时,您才输入“ 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.