C# 需要帮助添加以检查空值吗
需要帮助查找空值,我不能很好地解决这个问题。特别检查以查找空值,然后将输出显示为空值C# 需要帮助添加以检查空值吗,c#,C#,需要帮助查找空值,我不能很好地解决这个问题。特别检查以查找空值,然后将输出显示为空值 public int EXP; public static void Main(string[] args) { Console.Write("Check to see if its a prime number!strong text Enter a number! "); int Vo = Convert.ToInt32(Console.ReadLine()); int Va =
public int EXP;
public static void Main(string[] args)
{
Console.Write("Check to see if its a prime number!strong text Enter a number! ");
int Vo = Convert.ToInt32(Console.ReadLine());
int Va = Check_Prime(Vo);
if (Va == 0)
{
Console.WriteLine("not a prime number!", Vo);
}
else
{
Console.WriteLine("Is a prime number!", Vo);
}
Console.Read();
}
private static int Check_Prime(int Vo)
{
int L;
for (L = 2; L <= Vo - 1; L++)
{
if (Vo % L == 0)
{
return 0;
}
}
if (L == Vo)
{
return 1;
}
return 0;
}
public-int-EXP;
公共静态void Main(字符串[]args)
{
控制台。写入(“检查它是否是质数!强文本输入数字!”);
intvo=Convert.ToInt32(Console.ReadLine());
int Va=检查素数(Vo);
如果(Va==0)
{
WriteLine(“不是质数!”,Vo);
}
其他的
{
WriteLine(“是一个素数!”,Vo);
}
Console.Read();
}
专用静态整数检查素数(整数Vo)
{
int L;
对于(L=2;L在整数转换之前进行检查,否则它将返回0表示null
string userInput = Console.ReadLine();
if(string.IsNullOrEmpty(userInput))
{
Console.WriteLine("Your message");
}
int Vo = Convert.ToInt32(userInput);
// Rest of your code
如果要确保用户输入有效的整数,一种方法是在循环中获取用户输入,其退出条件是该输入是有效的int
。我通常通过使用帮助器方法来实现这一点。帮助器方法接受字符串
“提示”,在获取用户输入之前显示给用户
helper方法使用int.TryParse
方法,该方法接受string
值(在我们的示例中,我直接使用Console.ReadLine()
,因为它返回字符串
),并获取一个out int
参数,如果转换成功,该参数将设置为字符串的整数表示形式。如果转换成功,该方法本身将返回true
:
private static int GetIntFromUser(string prompt)
{
int value;
do
{
Console.Write(prompt);
} while (!int.TryParse(Console.ReadLine(), out value));
// If TryParse succeeds, the loop exits and 'value' contains the user input integer
return value;
}
这样做的好处是,该方法处理所有重试操作,您只需在主代码中调用它,并向用户提供提示,并且保证输入为整数:
public static void Main(string[] args)
{
Console.WriteLine("I will tell you if the number you enter is a prime number!\n");
int Vo = GetIntFromUser("Enter a whole number: ");
就在上面最后一行,如果用户试图输入一个无效的数字(或者什么都没有),程序只会不断询问他们,直到他们遵守:
我认为除了检查null或empty之外,还应该检查非数值
public static void Main(string[] args)
{
Console.Write("Check to see if its a prime number!strong text Enter a number! ");
string number = Console.ReadLine();
if(string.IsNullOrWhiteSpace(number))
{
Console.WriteLine("Input is empty.");
return;
}
int Vo;
bool success = int.TryParse(number, out Vo);
if(!success)
{
Console.WriteLine("Input is not an integer.");
return;
}
int Vo = Convert.ToInt32();
int Va = Check_Prime(Vo);
if (Va == 0)
{
Console.WriteLine("not a prime number!", Vo);
}
else
{
Console.WriteLine("Is a prime number!", Vo);
}
Console.Read();
}
您还可以检查输入是否为整数且小于0,并显示错误消息,因为质数仅为正数。但这将是一个附加检查。查找空值是什么意思?您是否收到空引用异常?当您点击ENTER键时,Console.ReadLine返回空字符串。它不返回空。仅当您按CTRL+Z时,它才会返回空。我认为您应该检查IsNullOrWhiteSpace