Char tryParse没有像我想的那样工作

本文关键字:工作 tryParse Char | 更新日期: 2023-09-27 18:21:39

我在c#中完成的一个方法有一些问题。我试图阻止用户输入除y和n之外的任何其他符号。它几乎可以按我的意愿工作,但用户仍然可以输入多个符号,然后就不工作了!如何检查char是否是多个char?我以为那次尝试解决了这个问题?谢谢

// 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();
                }
            }
        }
    }

Char tryParse没有像我想的那样工作

下面的代码"有效",因为它产生了预期的结果。

        char responseFoodItem;
        Console.Write("Enter if food item or not (y/n): ");
        if (char.TryParse(Console.ReadLine(), out responseFoodItem))
        {
            // Set true or false to variable depending on the response
            if ((responseFoodItem == 'y' || responseFoodItem == 'Y'))
            {
                Console.WriteLine("foodItem = true");
            }
            else if ((responseFoodItem == 'n' || responseFoodItem == 'N'))
            {
                Console.WriteLine("foodItem = false");
            }
            else
            {
                Console.WriteLine("Unrecognised input");
            }
        }
        else
        {
            Console.WriteLine("Invalid input");
        }

然而,其他人指出,如果您想将输入限制为单个键,那么使用ReadKey是更好的解决方案。这也意味着用户不必按Return/Enter键就可以接受输入。

char表示单个字符,因此How can I do to also check if char is more than one char? I thought the tryParse solved that?似乎有点荒谬。。。TryParse将尝试解析输入中的单个字符,如果值为null或长度>1,则会显式失败。

不检查字符,只检查字符串,例如:

string line = Console.ReadLine();
switch (line.ToUpperInvariant())
{
    case "Y":
        // Do work for y/Y
       break;
    case "N":
        // Do work for n/N
        break;
    default:
        // Show error.
        break;
}

char.TryParse只是尝试解析作为参数提供的字符串,它不会限制使用Console.ReadLine可以输入到控制台的字符数。

当用户输入多个字符时,char.TryParse将失败,因为Console.ReadLine返回的字符串不包含单个字符。

您应该使用Console.Read

如何检查char是否是多个char?

string line = Console.ReadLIne();
If(!string.IsNullOrEmpty(line) && line.Length > 1)

要读取单个字符,请使用Console.ReadChar()

Console.ReadLine允许用户键入任意长度的字符串并按enter键。

如何检查char是否是多个char?我以为那次尝试解决了这个问题?

从手册页面:

将指定字符串的值转换为其等效的Unicode字符。返回代码指示转换成功还是失败。。。。如果s参数为null或s的长度不是1,则转换失败。

您是否尝试过使用Console.ReadKey而不是ReadLine?

要检查用户是否插入了多个字符,您可以检查字符串长度,而不是使用char.TryParse

......
private void ReadIfFoodItem()
{
 string answer=string.empty;
 Console.Write("Enter if food item or not (y/n): ");
 answer=Console.ReadLine()
 if (answer.lenght>=1))
    {
           //error
          .......
    }   

这个答案应该会对您有所帮助:如何限制控制台输入的字符数?C#

控制台不限制用户输入(它确实限制了,但限制为256个字符),char.TryParse也不限制输入长度,它根本不做任何事情。

您可以尝试使用Console.ReadKey这只是用户的一次按键,你知道不会有超过一个字符。

为什么不与输入的字符串进行比较
为什么不简化比较呢?

using System.Linq;
private static string[] ValidAnswers = new string[]{ "y", "yes" };
// Method to check if item is food or not
private void ReadIfFoodItem() {
    Console.Write("Enter if food item or not (y/n): ");
    string ans = Console.ReadLine();
    // Checks if the answer matches any of the valid ones, ignoring case.
    if (PositiveAnswers.Any(a => string.Compare(a, ans, true) == 0)) {
        foodItem = true;
        selectedVATRate = 12; // Extra variable to store type of VAT
    } else {
        foodItem = false;
        selectedVATRate = 25; // Extra variable to store type of VAT
    }
}

或者,正如其他人所说,您可以使用Console.ReadKey().

使用Console.ReadKey()来限制字符数量。要测试是Y还是N,可以比较ASCII代码或使用正则表达式。