需要帮助找到null,我无法弄清楚这一点。具体检查找到一个null然后把输出说成是null
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;
}
在整数转换之前进行检查,否则返回0表示null。
string userInput = Console.ReadLine();
if(string.IsNullOrEmpty(userInput))
{
Console.WriteLine("Your message");
}
int Vo = Convert.ToInt32(userInput);
// Rest of your code
我认为除了检查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并显示错误消息,因为素数仅为正数。但这将是一个额外的检查。
如果要确保用户输入有效的整数,一种方法是在循环中获取用户输入,其退出条件是条目是有效的int
。我通常通过使用辅助方法来做到这一点。辅助方法接收string
“提示”,在获得输入之前显示给用户。
辅助方法使用int.TryParse
方法,它接受string
值(在我们的例子中,我直接使用Console.ReadLine()
,因为它返回一个string
),它采用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: ");
只有上面的最后一行,如果用户试图输入一个无效的数字(或根本没有输入),程序就会一直询问它们,直到它们符合: