Here is my code, for my if statements I want to have it between two values for example:
if(rating < 5 > 2);
So I'm saying i want it to only print the command if that value is below 5 but higher than 2. Is there a way to do this? Thank you for your time.
Here is my code.
public static void Main(string[] args)
{
Console.WriteLine("What would you rate starcraft out of 10?");
int rating = Console.Read();
if (rating < 5) ;
{
Console.WriteLine("Not good enough!");
Console.ReadLine();
}
if (rating > 5) ;
{
Console.WriteLine("OOOOOOOOO yeeeeeeee");
Console.ReadLine();
}
if (rating > 8) ;
{
Console.WriteLine("We are bestfriends now ;)");
Console.ReadLine();
CodePudding user response:
Use conditional logical AND operator &&
:
if (rating < 5 && rating > 2)
{
}
Or pattern matching (read more #1, read more #2):
if (rating is < 5 and > 2)
{
}
P.S.
You can refactor a bit with switch
expression and ordering the checks to remove some code repetition and improve readability (note that original code does not cover rating == 5
case compared to the following):
var rating = ...;
var message = rating switch
{
< 2 => "Terrible",
< 5 => "Not good enough!",
< 8 => "OOOOOOOOO yeeeeeeee",
_ => "We are bestfriends now ;)"
};
Console.WriteLine(message);
Console.ReadLine();
CodePudding user response:
To avoid complications, you can sort ratings' thresholds and then check them in order with a help of if ... else if
pattern, e.g. having
2 - Nightmare
5 - Not good enough!
8 - OOOOOOOOO yeeeeeeee
more - We are bestfriends now
We can put it as
if (rating <= 2) // 2 or less
Console.WriteLine("Nightmare");
else if (rating <= 5) // (2..5]
Console.WriteLine("Not good enough!");
else if (rating <= 8) // (5..8]
Console.WriteLine("OOOOOOOOO yeeeeeeee");
else // more than 8
Console.WriteLine("We are bestfriends now");
Console.ReadLine();