簡體   English   中英

如何在 C# 中要求用戶輸入有限次數

[英]How to ask for user input a limited number of times in C#

我是 C# 新手,我正在嘗試編寫一個程序,該程序從用戶那里獲取數字輸入選擇(從 1 到 13,因此它最多只能要求輸入 13 次),然后將用於檢查 CSV 文件用於匹配位置。 但是,我不知道該怎么做。 目前我有這個:

            Start: 
            Console.WriteLine("Please enter some Location IDs: ");
            int itemID = Convert.ToInt32(Console.ReadLine());

            if (itemID <= 13)
            {
                Console.WriteLine("Please Enter another ID: ");

            }
            else if (itemID > 13)

            {
                Console.WriteLine("There are only 13 locations available.");
                goto Start;
            }
            if (itemID == 0)
            {
                Console.WriteLine("Sorry, there is no Location 0.");

            }

我正在使用標簽返回到循環的開頭。 這是一個壞主意嗎? 任何幫助,將不勝感激。 干杯!

我正在使用標簽返回到循環的開頭。 這是一個壞主意嗎?

是的。 今天將是學習while好日子。 考慮while兩種方法:

(1) 你知道if會怎樣。 if(condition) statement評估condition ,如果為真,則執行statement一次

while做幾乎相同的事情。 while(condition) statement評估condition ,如果為真,則執行statement ,然后再次檢查condition ,...依此類推,直到condition為假。

(2)如果你理解跳轉,你可以表達while在條件goto while(condition) statement等同於:

Continue: if (!condition) goto Break;
statement
goto Continue;
Break:;

如果你可以用goto編程,你可以用while更清楚地編程同樣的事情。

但是,在您的特定情況下,您可能想要使用do循環,這是一個顛倒的while

do statement while(condition);

具有“執行語句,然后檢查條件;如果為真,再次執行語句...直到條件為假。 do具有語義的行為:

Restart: statement
Continue: if (condition) goto Restart;
Break:;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM