2012-07-04 40 views
1

我正在寻找一种有用的方法,并有助于捕获错误输入。如果输入不是1或2,我需要处理。或者 - 或者只是任何字母。我已经尝试赶上,没有什么似乎工作:/如何捕获从字符串解析的int错误?

有人有一个想法让我尝试?我很乐意提供任何建议! Thx提前!

问候

到目前为止,我已经写的代码看起来是这样的:

console.WriteLine(); 
Console.Write("Make your choice: "); 


int myinput = int.Parse(Console.ReadLine()); 

if (myinput == 1) 
{ 
FirstEvent(); 
} 
if (myinput == 2) 
{ 
SecondEvent(); 
} 

回答

5

通常我们使用的TryParse方法

int myinput = 0; 
if(false == int.TryParse(Console.ReadLine(), out myInput)) 
    // Error, not an integer 
    Console.WriteLine("Please input 1 or 2"); 
else 
{ 
    if (myinput == 1) 
    { 
     FirstEvent(); 
    } 
    else if (myinput == 2) 
    { 
     SecondEvent(); 
    } 
    else 
     Console.WriteLine("Please input 1 or 2"); 
} 
+1

是否有一个原因,我不知道写if(false == int.TryParse(Console.ReadLine(),out myInput))而不是if(!int.TryParse(Console.ReadLine(),out myInput))? –

+1

@FrancescoBaruchelli,没有没有具体原因。我更喜欢这种方式,因为(在我这个年龄段)有时候NOT角色会逃避我的视力。 – Steve

+0

我低头看着你的功夫!感谢百万史蒂夫!它像一个魅力!祝你有美好的一天!关于 – user1501127