我在c#中完成的方法有一些問題。我試圖阻止用戶輸入任何東西,然後Y和N。它幾乎是我想要的,但用戶仍然可以輸入多個符號,然後它不起作用!我該怎麼做才能檢查char是否超過一個字符?我認爲tryParse解決了這個問題?謝謝!Char tryParse沒有按照我的想法工作?
// Method to check if item is food or not
private void ReadIfFoodItem()
{
Console.Write("Enter if food item or not (y/n): ");
if (char.TryParse(Console.ReadLine(), out responseFoodItem))
{
if(Char.IsNumber(responseFoodItem))
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
else
{
// Set true or false to variable depending on the response
if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
{
foodItem = true;
selectedVATRate = 12; // Extra variable to store type of VAT
}
else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
{
foodItem = false;
selectedVATRate = 25; // Extra variable to store type of VAT
}
else
{
Console.WriteLine(errorMessage);
ReadIfFoodItem();
}
}
}
}
你當然希望有很多! – leppie 2012-01-27 09:58:13
如果你想限制用戶輸入1個字符,你不能只使用'Console.Read()'? – annonymously 2012-01-27 10:00:46
也許我應該補充一點,我是C#的新手,這個解決方案並不是最好的! :) – 2012-01-27 10:02:31