3D-kreativ
3D-kreativ

Reputation: 9297

Char tryParse not working as I thought?

I have some problem with a method that I have done in c#. I'm trying to stop user from entering anything else then y and n. It's almost working that I want, but user can still enter more than one sign, and then it doesn't work! How can I do to also check if char is more than one char? I thought the tryParse solved that? Thanks!

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

Upvotes: 0

Views: 2418

Answers (10)

CSharpened
CSharpened

Reputation: 12574

Use Console.ReadKey() to limit the amount of characters. To test whether you have a Y or an N then you can compare the ASCII codes or use a regular expression.

Upvotes: 0

ChrisF
ChrisF

Reputation: 137148

The following code "works" in that it produces the expected results.

        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");
        }

However, has others have pointed out using ReadKey is a better solution if you want to limit the input to a single key. It also means that the user doesn't have to press the Return/Enter key for the input to be accepted.

Upvotes: 1

ANeves
ANeves

Reputation: 6365

Why not comparing to the input'ed string?
And why not simplifying the comparison?

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
    }
}

Alternatively, as others said, you can use Console.ReadKey().

Upvotes: 0

rgargente
rgargente

Reputation: 1840

You can try using Console.ReadKey It's just one keystroke for the user and you know there won't be more than one char.

Upvotes: 0

Pieter
Pieter

Reputation: 3399

This answer should help you: How can I limit the number of characters for a console input? C#

The console does not limit the user input (well it does, but to 256 characters), nor does char.TryParse which doesn't do anything at all to limit the input length.

Upvotes: 0

Matthew Abbott
Matthew Abbott

Reputation: 61589

char represents a single character, so How can I do to also check if char is more than one char? I thought the tryParse solved that? seems a bit nonsensical... TryParse will try and parse a single character from your input and will explicitly fail if the value is null or has a length > 1.

Instead of checking a character, just check the string, e.g.:

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;
}

Upvotes: 1

Massimiliano Peluso
Massimiliano Peluso

Reputation: 26737

To check it the user has inserted more then one char you could check the string length instead of use 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
          .......
    }   

...............

Upvotes: 0

Paolo
Paolo

Reputation: 22638

Console.ReadLine allows users to type a string of any length and press enter.

How can I do to also check if char is more than one char? I thought the tryParse solved that?

From the manual page:

Converts the value of the specified string to its equivalent Unicode character. A return code indicates whether the conversion succeeded or failed....The conversion fails if the s parameter is null or the length of s is not 1.

Have you tried using Console.ReadKey instead of ReadLine?

Upvotes: 0

Tigran
Tigran

Reputation: 62246

How can I do to also check if char is more than one char?

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

for reading a single char use Console.ReadChar() instead.

Upvotes: 0

Khaled Nassar
Khaled Nassar

Reputation: 884

char.TryParse simply tries to parse the string supplied as an argument, it does not limit the number of characters that you can input to the console using Console.ReadLine.

When the user inputs more than a single character, char.TryParse will fail because the string returned by Console.ReadLine doesn't contain a single character.

You should use Console.Read instead.

Upvotes: 0

Related Questions