Using enum as a variable (?) [duplicate] - c#

This question already has answers here:
Convert a string to an enum in C#
(29 answers)
Closed 3 years ago.
I have a problem about some simple code in console. Precisely I created a public enum called Year which contains 4 seasons (obvious). I want the program to ask at the beginning what is the season of the year and then generate an answer to each option. The problem is I don't know how to convert my string input to each option of this enum. Maybe it will be more clear if i show you the code (it's short).
Console.WriteLine("What time of year is it?");
var input = Console.ReadLine();
//earlier it was just
//time = Year.Winter;
switch (time)
{
case Year.Autumn:
Console.WriteLine("You're gonna have to grab the leaves");
break;
case Year.Summer:
Console.WriteLine("Let's go to the beach");
break;
case Year.Winter:
Console.WriteLine("Better to warm up at home");
break;
case Year.Spring:
Console.WriteLine("Best time of the year!");
break;
default:
Console.WriteLine("I don't know this time of year");
break;
}
I want to make something like this but dunno what to put inside this switch statement because I can't just put there my string 'input'. Is it possible in the way I am thinking of it?

You can parse a try to parse a string into an Enum by using one of the Enum class.
In particular, you can use the typed method TryParse in this eay
var ignoreCase = true; // decide this
if (Enum.TryParse<MyEnum>("my string", ignoreCase, out var r))
// use r
else
Console.WriteLine("Please enter the correct value.");

You can use string contain() function before the switch statment like below i haven't tested if it works like this (nested) if not you have to use if and else if condition
time = input.Trim().Contains("winter") ? Year.Winter: (input.Trim().Contains("summer") ?Year.Summer :(input.Trim().Contains("autumn") ?Year.Autumn:i(nput.Trim().Contains("autumn") ?Year.Autumn: null)));
The other thing you can do is give user option like 1 Year.Autumn,2 Year.Summer,3 Year.Winter,4 Year.Spring and get a number on which you can use the switch statment

Related

How do I check if the user input is strictly numbers, using the bool type? [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 5 years ago.
I defined a string data type. Prompted the user to enter 10 numbers. e.g Console.Write("Enter your cell number: ");
I want to know how to validate the string and make sure the user entered numbers only
Best option would be use regular expression to much exactly 10 digits:
Regex pattern = new Regex(#"^\d{10}$");
if(pattern.isMatch(input))
{
//Do something
return true;
}
Another option is to use Int64.TryParse, read more here, but that additional checks are needed, to verify that result had 10 digits (no more, no less), number is not negative etc.
bool result = Int64.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}

Case Insensitive Interpretation C# [duplicate]

This question already has answers here:
How can I do a case insensitive string comparison?
(9 answers)
LINQ Contains Case Insensitive
(11 answers)
Closed 5 years ago.
I'm making a text game, and I have one method for getting the input from the player and another for processing that input. However, it only works if the player types the command all in lowercase. I want it to ignore case.
public string GetInput()
{
var Test = true;
while (Test)
{
response = Console.ReadLine();
if (validWords.Contains(response))
{
Test = false;
ProcessInput(response);
}
else
{
Console.WriteLine("I'm sorry, I do not understand.");
}
}
return response;
}
public void ProcessInput(string response)
{
switch (response)
{ //Switch statements for responses here
}
}
I've tried using a few other responses I've found here, but they all still only work with lowercase input(using LINQ, string.IndexOf/Equals/etc.). Ideas?
Use string comparer which ignores string case as second parameter for Contains method:
validWords.Contains(response, StringComparer.OrdinalIgnoreCase)
You can make every input you receive, Lower-Case, using ToLower().
Example:
string response = Console.ReadLine().ToLower();
You can add .ToLower() after the readline, as followed:
response = Console.ReadLine().ToLower();
Everything read in from the console will be in lowercase.
You can read more about the ToLower method in the MSDN documentation.
Furthermore, also see the following question if you expect input of certain cultures: string.ToLower() and string.ToLowerInvariant().
Change the text you have to lower using .ToLower().
You're currently using if (validWords.Contains(response)) to check whether the user's response is contained within your validWords list. (I'm assuming).
What you can do is use the following LINQ expression:
if (validWords.Where(w => w.ToUpper().Equals(response.ToUpper())).Count() == 1)
This validates against both upper case strings.

C# if statement readline must equal number [duplicate]

This question already has answers here:
How can I validate console input as integers?
(10 answers)
Closed 8 years ago.
I can't figure out what to put in brackets to make my program check if the input was number. I would like to return an error if not, and restart the process. Any suggestions?
bool running = true;
Console.Write("Enter the number of victims so we can predict the next murder, Sherlock: ");
while (running)
{
victimCount = int.Parse(Console.ReadLine());
if (/*I want victimCount only to be accepted if it's a number*/)
{
Console.Write("\nThat's an invalid entry. Enter a correct number!: ");
}
else
{
running = false;
}
}
I want victimCount only to be accepted if it's a number
You can use int.TryParse method instead. It returns boolean value that your value is a valid int or not.
string s = Console.ReadLine();
int victimCount;
if(Int32.TryParse(s, out victimCount))
{
// Your value is a valid int.
}
else
{
// Your value is not a valid int.
}
Int32.TryParse method uses NumberStyles.Integer by default. That means your string can have;
Leading CurrentCulture's sign. (PositiveSign or NegativeSign)
Leading white spaces.
Trailing white spaces
as a number stye.
Try this:
int victimcount;
bool is Num = int.TryParse(Console.ReadLine(), out victimcount);
If `isNum` is true then the input is an integer. Use this for your check. At the same time, if the parse succeeds, the parsed value gets assigned to the `victimcount` variable (0 is assigned if it fails).

How many days user has been alive calculator

I have a snipped of code that I wrote that calculates how long the user has been alive. But the problem is, the program goes to hell if the user doesn't enter a integer e.g January or something else. I need to know how to stop this.
int inputYear, inputMonth, inputDay;
Console.WriteLine("Please enter the year you were born: ");
inputYear = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the Month you were born: ");
inputMonth = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the day you were born: ");
inputDay = int.Parse(Console.ReadLine());
DateTime myBrithdate = new DateTime(inputYear,inputMonth, inputDay);
TimeSpan myAge = DateTime.Now.Subtract(myBrithdate);
Console.WriteLine(myAge.TotalDays);
Console.ReadLine();
if the user doesn't enter a integer e.g January or something else
You can use Int32.TryParse method then..
Converts the string representation of a number in a specified style
and culture-specific format to its 32-bit signed integer equivalent. A
return value indicates whether the conversion succeeded.
Console.WriteLine("Please enter the Month you were born: ");
string s = Console.ReadLine();
int month;
if(Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out month))
{
// Your string input is valid to convert integer.
month = int.Parse(s);
}
else
{
// Your string input is invalid to convert integer.
}
Also TryParse method doesn't throw any exception and that's why you don't need to use any try-catch block with it.
This is far above my level, I have no idea what is going on here.
Ok. I try to explain a little bir more deep.
What you complain is the users input right? Beucase you said, you want to put int as an input. Not string like "January" or "May" etc..
When you read input with Console.ReadLine() method, it returns a string as a return type, not int. Doesn't matter user put as an input 3 or January, this method returns them as a string regardless what they are type is.
3 and January are strings in this case. But how we check these strings are actually convertable to an integer value? This is the part of why we using Int32.TryParse method. This method checks these inputs are convertable to integers or not so we can use this integer in DateTime constructor as a real integer.
This is because you are using int.Parse(Console.ReadLine()); - the int stands for integer. Well you could put a try catch block arround your code.
The original code would stand in the try block, because you want to try to run it- but if an error accours ( e.g. user types jan), the catch block handles the error and your program could go on without troubles. 

Using an enum and a switch statement c#

I am using an enum as my options for a switch statement and it works. The problem is if the user enter a non valid option the program crashes. What should I add so that the default is used?
my enum class
public enum Options : byte
{
Display = 1,
Add,
Toggle,
Max,
Mean,
Medium,
Exit
}
in main my switch statement
string volString = Console.ReadLine();
Options options = (Options)Enum.Parse(typeof(Options), volString);
// this is the line that is giving me the runtime error. Since other options are not found
in the enum the program crashes.
switch (options)
{
case Options.Display: //dispaly regular time
case Options.Toggle://toggle
default:
Console.WriteLine("entry blah blah");
break;
Instead of Enum.Parse use Enum.TryParse... this will return a boolean to say if the text can be converted into your enum. If it's true run your switch otherwise inform the user that they entered an invalid string.
Use Enum.TryParse instead:
Options options;
if(!Enum.TryParse(volString, out options)) {
// It wasn't valid input.
}
How about:
Options value;
if(!Enum.TryParse(volString, out value)) // note implicit <Options>
value = Options.SomeDefaultValue;
Look at Enum.TryParse(...) you can use this to check for invalid strings.

Categories