簡體   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