繁体   English   中英

需要添加帮助以检查null

[英]Need Help adding to check a 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

如果要确保用户输入有效的整数,则一种方法是在循环中获取用户输入,该循环的退出条件是该条目是有效的int 我通常通过使用辅助方法来执行此操作。 helper方法采用string “ Prompt”,该string在获得输入之前会显示给用户。

helper方法使用int.TryParse方法,该方法接受一个string值(在我们的示例中,我直接使用Console.ReadLine() ,因为它返回一个string ),并且它使用out int一个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或空值之外,还应该检查非数字值。

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,并显示错误消息,因为质数是仅afaik的正数。 但这将是额外的检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM