// if user input is negative
if (h < 0)
{
// assign absolute version of user input
number = Math.Abs(n);
pictureBox14.Visible = true;
}
else
{
// else assign user input
number = n;
number = 0; // if user input is not an int then set number to 0
pictureBox6.Visible = true;
}
验证为 int ONLY 的正确代码是什么?该整数是我想在文本框中输入的唯一整数,然后会出现图片框。
使用 int。TryParse 方法
int value= 0;
if (int.TryParse(n, out value))
{
if (value< 0)
number = Math.Abs(value);
else
number = value;
}
不需要
复杂的 if 语句。你可以这样做。
int number = 0;
bool isValid = int.TryParse(userInputString, out number);
number = Math.Abs(number);
if (isValid)
{
pictureBox14.Visible = true;
}
首先要解析用户输入,然后验证范围:
int ExampleFunc( string userInput )
{
int nVal;
if( int.TryParse( userInput, out nVal ) )
{
return Math.Abs( nVal );
}
else return 0;
}
没有理由检查数字是否为负数,只需始终使用绝对值即可。 如果从文本输入传递给它的字符串无法正确转换,Convert
将返回 0 值,因此此代码只需一行即可处理您的问题。如果希望图片框基于 int 值显示,请在转换后进行测试。
int number = Math.Abs(Convert.ToInt32(textInput));