本文介绍了格式异常,我做错了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望我的应用程序,当有人输入信件或不是数字的某个信息时,会显示以下消息:您必须输入一个数字!
I want that my app, when someone enters a letter, or sometehing that isn't a number, shows this message: "You must enter a number!"
void Button_guessClick(object sender, EventArgs e)
{
try
{
int guess = Convert.ToInt32(textBox_guess.Text);
}
catch(FormatException ex)
{
MessageBox.Show("You must enter a number!");
}
if (guess > number)
{
MessageBox.Show("The number is smaller!");
}
if (guess < number)
{
MessageBox.Show("The number is bigger!");
}
if (guess == number)
{
MessageBox.Show("Bravo, you have guessed it");
Application.Exit();
}
}
推荐答案
int guess;
if (!int.TryParse(textbox_guess.Text, out guess))
{
MessageBox.Show("You must enter a number!");
}
else
{
if (guess > number...
缩进还原 - OriginalGriff [/ edit]
[edit]Indentation reverted - OriginalGriff[/edit]
try{
int guess = Convert.ToInt32(textBox_guess.Text);
}
catch(FormatException ex){
MessageBox.Show("You must enter a number!");
return; // this will return from your function no more messages will show..
}
你最好使用 Int32.TryParse
作为其他答案指出。
这篇关于格式异常,我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!