[英]How to ask for user input with letters (a-z) only without special characters or numbers in C#
[英]How to ask the user to input numbers only in integer?
我想要求用戶輸入一個數字,包括一個 if 語句選項,如果他輸入字母,最后一個問題將再次被問到我試過這個,但似乎它只適用於字符串
Console.Write("Write a number:");
int num = Convert.ToInt32(Console.ReadLine());
if (!int.TryParse(age, out num))
while(!int.TryParse(age, out num))
{
Console.WriteLine(...);
// ....
}
讓我們為此提取方法:我們將要求用戶輸入有效值,直到他或她提供為止。 所以我們有一個循環:
private static int ReadInteger(string question) {
// Keep asking...
while (true) {
if (!string.IsNullOrWhiteSpace(question))
Console.WriteLine(question);
// ... until valid value provided
if (int.TryParse(Console.ReadLine(), out int result))
return result;
Console.WriteLine($"Sorry, not a valid integer value; please, try again.");
}
}
然后你可以將它用作
int age = ReadInteger("Please, input age");
我在我當前的項目中使用了一個函數,它可能會幫助你,它只是檢查輸入字符串是否只包含數字:
bool isDigitsOnly(string inputString)
{
foreach (char c in inputString)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
您可能需要稍微修改一下以滿足您的需要,但它應該可以正常工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.