我在这里有一种进入星期几的方式,但如果我输入的数字值不是1-7,程序就会结束。我想有办法触发捕获。
namespace DaysOfTheWeek
{
class Program
{
public enum EDay
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday,
}
static void Main(string[] args)
{
try
{
Console.WriteLine("Hello! A week has 7 days! What day of this week is it?");
EDay pickDay = (EDay)Enum.Parse(typeof(EDay), Console.ReadLine(), true);
Console.WriteLine("The day you picked was {0}", pickDay - 1);
Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("Please enter an actual numerical day of the week.");
Console.ReadLine();
}
}
}
}
答案 0 :(得分:1)
您可以使用IsDefined()
之类的
$connection->query('xdrop procedure if exists parents');
$connection->query('
create procedure parents(in parent int(11),in name varchar(22))
begin
set @parent=parent;
drop temporary table if exists ids;
create temporary table ids(id int(11));
while @parent<>0 do
prepare statement from concat("select related into @parent from ",name," where id=?");
execute statement using @parent;
insert into ids(id) values(@parent);
end while;
select*from ids;
end;
');
$connection->query('drop function if exists counted');
$connection->query('
create function counted(parent int(11),name varchar(22))
returns int(11)
begin
call parents(parent,name);
return (select count(*) from ids);
end;
');
$fetch=$connection->query('select counted(3,"category");')->fetchall();
答案 1 :(得分:1)
如果输入预期为“数字”,则应使用int.Parse
。并且,int.TryParse
将帮助您捕获无数字输入:
var input = Console.ReadLine();
if (int.TryParse(input, out var value))
{
if (1 <= value && value <= 7)
{
Console.WriteLine("The day you picked was {0}", (EDay)value - 1);
}
else
{
Console.WriteLine("PLease enter an number between 1 - 7");
}
}
else
{
Console.WriteLine("Please enter an actual numerical day of the week.");
}
如果您还希望接受“monday”之类的输入并添加数值,也可以使用Enum.TryParse
。如果您希望1
映射到Monday
:
Monday = 1,
如果您对(EDay)value
解决方案进行了上述更改,也可以直接使用int.TryParse
。
答案 2 :(得分:0)
在将其转换为枚举之前,您可能希望首先阅读他们输入的内容。
这是一个简单的例子:
try
{
Console.WriteLine("Hello! A week has 7 days! What day of this week is it?");
var dayEntered = Console.ReadLine();
int dayInt;
bool success = int.TryParse(dayEntered, dayInt);
if(!success || dayInt < (int)EDay.Monday || dayInt > (int)EDay.Sunday)
{
//either throw a new exception to go into your catch block or just have logic here.
}
EDay pickDay = (EDay)dayInt;
Console.WriteLine("The day you picked was {0}", pickDay - 1);
Console.ReadLine();
}
catch (Exception)
{
Console.WriteLine("Please enter an actual numerical day of the week.");
Console.ReadLine();
}