Why does this c# code not work? I cannot figure it out.
I am struggling with finding a simple c# code example that can convert/parse string values "y" and "n" from console.readline() to boolean true or false statements and save this as a boolean data type.
using System;
public class Demo
{
public static void Main()
{
Console.WriteLine("Input y");
string answer = Console.ReadLine();
if (answer == "y")
{
bool InputY = bool.Parse(answer);
Console.WriteLine("You have saved a 'True' statement in the boolean with name of 'InputY'");
}
else
{
Console.WriteLine("Any random text");
}
}
}
CodePudding user response:
Boolean.Parse (selective quotes):
Returns
Booleantrue if value is equivalent to
TrueString; false if value is equivalent toFalseString.Exceptions
FormatException
valueis not equivalent toTrueStringorFalseString.
Remarks
This field is equal to the string
"True".
Remarks
This field is equal to the string
"False".
As you can see Parse only accepts the strings "True" or "False", it's not what you need.
But ... you are already on the branch that deals with truthy input if (answer == "y") so you do not need to do any other kind of parsing.
You could do something like this:
if (anwser.ToLower() == "y")
{
// deal with answer yes
}
else if (answer.ToLower() == "n")
{
// deal with answer no
}
else
{
// deal with answer outside of y/n
}
If you want to have a boolean representing their answer then similarly you can create a function:
bool ParseYNString(string stringToParse)
{
if (stringToParse.ToLower() == "y")
return true;
if (stringToParse.ToLower() == "n")
return false;
throw new FormatException(/* message */);
}
You can go one step further and create a function to get the Y/N input:
bool GetYNFromConsole(string prompMessage, string tryAgainMessage)
{
Console.Write(prompMessage);
while (true)
{
string line = Console.ReadLine();
if (line.ToLower() == "y")
return true;
if (line.ToLower() == "n")
return false;
Console.Write(tryAgainMessage);
}
}
That is of course just a starting point. You should customize it to your needs.
CodePudding user response:
bool.Parse(string) expects the string to be "true" or "false". You are still passing it "y", which cannot be parsed as true or false.
InputY could simply be set as
InputY = answer == "y";
if (InputY) { Console.WriteLine("..."); }
CodePudding user response:
Technically, you can put just
bool InputY = answer == "y";
if you are looking for elaborated design, you can extract a method:
private static readonly Dictionary<string, bool> s_KnownBools =
new(StringComparer.OrdinalIgnoreCase) {
// Add all synonyms for "true" here
{ "y", true },
{ "yes", true },
{ "t", true },
{ "true", true },
// Add all synonyms for "false" here
{ "n", false },
{ "no", false },
{ "f", false },
{ "false", false },
};
private static bool TryParseBool(string value, out bool result) =>
s_KnownBools.TryGetValue(value?.Trim() ?? "", out result);
private static bool ReadBool(string title) {
while (true) {
if (!string.IsNullOrWhiteSpace(title))
Console.WriteLine(title);
if (TryParseBool(Console.ReadLine(), out bool result))
return result;
Console.WriteLine("Not a valid answer. PLease, try again.");
}
}
then you can use it as
public static void Main() {
bool inputY = ReadBool("Input y");
if (answer) {
Console.WriteLine("You have saved a 'True' statement in the boolean with name of 'InputY'");
}
else {
Console.WriteLine("You have saved a 'False' statement in the boolean with name of 'InputY'");
}
}
