繁体   English   中英

C# 如果用户输入字符则返回数值

[英]C# Return numeric values if the user enters characters

我是 C# 的新手并且正在玩循环,我只想知道如何将变量userTarget设置为等于 integer 值,以防用户输入字符串,我尝试了 TryParse 方法,但我不知道我是否真的明白我在做什么。

static void Main()
{
    string userChoice = string.Empty;

    do
    {
        Console.WriteLine("Please enter your target?");
        int userTarget = int.Parse(Console.ReadLine());

        int start = 0;

        while (start <= userTarget)
        {
            Console.Write(start + " ");
            start += 2;
        }

        do
        {
            Console.WriteLine("Do you want to continue?");
            userChoice = Console.ReadLine().ToUpper();

            if (userChoice != "YES" && userChoice != "NO")
            {
                Console.WriteLine("Invalid choice, please say yes or no");
            }

        } while (userChoice != "YES" && userChoice != "NO");

    } while (userChoice == "YES");

}

TryParse绝对是 go 供用户输入的方式

将数字的字符串表示形式转换为其等效的 32 位有符号 integer。 返回值指示操作是否成功。

持续验证示例

int userChoice = -1;

...

Console.WriteLine("Please enter your target?");
while (!int.TryParse(Console.ReadLine(), out userTarget))
    Console.WriteLine("You had one job, enter a target...");

Console.WriteLine($"You entered : {userChoice}");

暂无
暂无

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

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