Testing Values For Multiple Conditions in C# - c#

I am having some difficulty finding out what's wrong with my code. I am trying to create a console app in C#. The program is supposed to ask the user to to input 3 numbers. All of the number must be greater than 0. The first number should be even, the second should be whole, and the third should be odd. My syntax seems to be correct, however, when I run the program, it seems to ignore the if (userInput > 0) part. Here is my code:
class Program
{
static void Main(string[] args)
{
try
{
int userInput;
Console.WriteLine("Please enter an even number.");
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput > 0 && !isEven(userInput))
return;
Console.WriteLine("Please enter a whole number.");
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput > 0)
Console.WriteLine("Please enter an odd number.");
userInput = Convert.ToInt32(Console.ReadLine());
if (userInput > 0 && isEven(userInput))
return;
Console.WriteLine("Congratulations!");
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
catch { }
}
static bool isEven(int value)
{
if (value % 2 == 0)
return true;
else
return false;
}
}
If anyone could tell me how to properly test both conditions I would be eternally greatful. Thanks.

Your requirements for the first number entered are essentially:
The number must be both positive and even.
The inverse of that is:
If the number is not positive, OR it is not even, then it is not valid.
Your check says
If the number is positive AND it is odd, then reject it
Meaning any number that is zero, negative, or even is valid.
What we have here is an application of DeMorgan's Law. It states that:
!(A && B)
is equivalent to
!A || !B
So if a valid number is even AND positive, then an invalid number is not even OR not positive (not positive is less than or equal to zero).

Problem : you are checking for one Valid and other invalid scenario with Logical AND.
Solution : you need to use both invalid scenarios with Logical OR.
asper your requirement program should not proceed if any one of the following rule breaks:
a. userinput should be > 0
b. userinput should be odd,whole and even
1. Replace This:
if (userInput > 0 && !isEven(userInput))
With This:
if (userInput <= 0 || !isEven(userInput))
2. Replace This:
if (userInput > 0 && isEven(userInput))
With This:
if (userInput <= 0 || isEven(userInput))

Based on the way you've structured your program, there is likely supposed to be a return statement after the second if, IE:
if (userInput > 0)
return;
However, this still does not address the problem that what you are probably trying to say is:
if (userInput <= 0)
return;
Or somewhat more directly translated from English:
if (!(userInput > 0))
return;
This change of sign applies to your other if statements as well, as others have mentioned.

Check
if (userInput <= 0 || !isEven(userInput))
return;
Since you want to quit when either the number is not positive OR the number is not even.
De Morgan's laws tell you how you can invert a logical expression. You do it by replacing each term by it's negated term and by replacing the AND's by OR's and vice versa.
So you could also write
if (userInput > 0 && isEven(userInput)) {
// The user input is ok, continue
} else {
return;
}
userInput <= 0 is the negation of userInput > 0.
De Morgan's laws
NOT(A AND B) = NOT(A) OR NOT(B)
and
NOT(A OR B) = NOT(A) AND NOT(B)

Related

Cant get while loop to check if my userinput equals some numbers

This is the piece of code I am talking about. So I want the user only to be able to write 1 or 2 or else the while loop will never break. The problem is that for some reason the loop just never breaks, even if I write 1 or 2.
while (caseSwitch != 1 || caseSwitch != 2)
{
Console.Write("Please write a number: ");
Int32.TryParse(userInput = Console.ReadLine(), out caseSwitch);
}
caseSwitch has an any time only a single value so it will always be either not 1 or not 2. Replace || with &&. Meaning you loop as long as caseSwitch is not 1 and is not 2. The moment it is one of them it halts.
while (caseSwitch != 1 && caseSwitch != 2)
{
Console.Write("Please write a number: ");
Int32.TryParse(userInput = Console.ReadLine(), out caseSwitch);
}
Note: there is another solution to this problem using De Morgan's law.
while (!(caseSwitch == 1 || caseSwitch == 2))
{
Console.Write("Please write a number: ");
Int32.TryParse(userInput = Console.ReadLine(), out caseSwitch);
}

c# cant run two functions in a loop?

What i want to do is to make it that inside a loop, the computer checks whether the number entered is firstly not a decimal, and at the same time i want to make sure that the number is within the range 1 - 100. My code now works in regards to having the first function about the number not being a decimal, so when i enter a decimal, an error message is displayed that tells the user to keep adding another number until an integer is added, and it then runs to the next part. However it doesn't seem to work when i put in a number outside of the range, the error message doesn't pop up and the conditions just don't seem to work. What i want to know is how do i get these two parts, the decimal and the range checking to work simultaneously. I'm really new to coding so could any explanations be simple so that i could understand. Thank you in advance!
string inputcost;
string inputmoney;
int validcost;
int validmoney;
int changereq;
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: ");
inputcost = Console.ReadLine();
bool result = int.TryParse(inputcost, out validcost);
while (!int.TryParse(inputcost, out validcost))
{
if (result == true )
{
Console.Write("Valid Value");
}
if (result == false)
{
Console.Write("You Cannot Enter Decimals. Please Enter A Valid Integer Value.");
Console.WriteLine();
inputcost = Console.ReadLine();
}
if (validcost < 100 && validcost > 1)
{
Console.Write("valid value");
}
else
{
Console.Write("invalid value.please enter a number between 1 and 100 ");
Console.ReadLine();
}
}
The line
while (!int.TryParse(inputcost, out validcost))
means that you enter the while loop only when the user types something that cannot be converted to an integer. If it is a valid integer the code inside the while loop is never reached and thus, your test on the valid range is never executed
Instead put everything inside the an infinite loop and provide a way to break the program (type x to quit)
while (true)
{
Console.Write("Please Enter The Cost, In Pennies, Of The Item You Have Purchased: (type x to quit)");
inputcost = Console.ReadLine();
// Check if the user wants to stop executing the program
if(inputcost == "x")
break;
// Check if it is a valid integer
bool result = int.TryParse(inputcost, out validcost);
if (!result)
{
Console.WriteLine("You Cannot Enter Decimals (or strings). Please Enter A Valid Integer Value.");
}
else if (validcost > 100 || validcost < 1)
{
Console.WriteLine("invalid value.please enter a number between 1 and 100 ");
}
else
{
Console.WriteLine("Valid value");
// other code block that works with the input number....
}
}
Alternativly use another condition for your loop, something that first checks for an integer and afterwards if it is in range:
while (!int.TryParse(inputcost, out validcost)) || validCost < 1 || validCost > 100)
{
Console.WriteLine("Please enter an integer between 1 and 100");
inputCost = Console.ReadLine();
}
All the code that should be executed when your inout is valid should now gow beyond the loop, not inside it.

Operator '>' and '<' cannot be applied to operands of type 'string' and 'string' C#

C# program made in Visual Studio 2015 that asks the user to guess a number from 1-10 that will tell the user if the guess was right, greater than or lesser than the value that must be guessed.
static void Main(string[] args)
{
string rightGuess = "7";
Console.WriteLine("Guess the right number from 1-10: ");
string userGuess;
userGuess = Console.ReadLine();
{
if (userGuess == rightGuess)
Console.WriteLine("You guessed right!");
else if (userGuess > rightGuess)
Console.WriteLine("Wrong guess. Your guess was greater than the right guess.");
else (userGuess < rightGuess)
Console.WriteLine("Wrong guess. Your guess was lesser than the right guess.");
}
}
The program returns following errors in Visual Studio 2015:
Have researched about an hour on Google how to solve the errors but none of the solutions fixed the errors.
You need to compare integers rather than strings (to achieve that kind of compare), change this lines to:
int rightGuess = 7;
int userGuess = int.Parse(Console.ReadLine());
and it will work. Of course you can add int.TryParse and check if input was actually an int
int userGuess;
if(int.TryParse(Console.ReadLine(), out userGuess))
{
... do your logic
}
else
{
Console.WriteLine("Not a number");
}
You should be using the right data type to compare
int rightGuess = 7;
Console.WriteLine("Guess the right number from 1-10: ");
int userGuess;
userGuess = int.Parse(Console.ReadLine());
{
if (userGuess == rightGuess)
Console.WriteLine("You guessed right!");
else if (userGuess > rightGuess)
Console.WriteLine("Wrong guess. Your guess was greater than the right guess.");
else (userGuess < rightGuess)
Console.WriteLine("Wrong guess. Your guess was lesser than the right guess.");
}
Think like this when you say "Mohit" is greater than "Mikex64" does it make any sense. No
But 2 is greater than 1 make sense. thus we can write it like 2 > 1 but cannot write "Mohit" > "Mikex64" thus you are getting this error message.
Edit: edited the "greater than" and "lesser than" operands from code to be accurate as I first wrote them wrong way.
either convert the string to numeric values using int.Parse/TryParse or use String.CompareTo().

C# Validation for specific input

I'm kinda new to this thread, but in short summary i'm having trouble with a small validation issue. Basically, i'm attempting to make a simple validation program that will collect a user's input and then determine if the input is valid in terms of, input being correctly implemented, the number being positive, and the number having to be either 0, 1, 2, 3, 4 or 5.
The overall program runs, but the issue i'm facing is every form of input is deemed an error, thus displaying my error statement, even if it is a valid input like 5 for example. I feel like there is a small mistake,i have made that is causing this, So is there any suggestions?
int user_input;
int count = 0;
do
{
Console.Write("\n\nUser Input:"
if ((int.TryParse(Console.ReadLine(), out user_input) == false)||(user_input < 0 || user_input != 0 ||user_input != 1 || user_input != 2
|| user_input != 3 || user_input != 4 || user_input != 5))
{
Console.WriteLine("Error : the action entered is not a valid number.");
count = 0;
}
else
count = 1;
Your mistake is because you use OR operator.
For example user print 3. In your statements one condition return false (input != 3), but all others return true.. That's why you always go into if condition..
You can use AND operator, but I can recommend you to simplify your condition. It will be more understandable and readable:
var count = 0;
do
{
Console.Write("\n\nUser Input:");
int user_input;
if ((int.TryParse(Console.ReadLine(), out user_input) == false) || (user_input < 0 || user_input > 5))
{
Console.WriteLine("Error : the action entered is not a valid number.");
count = 0;
}
else
count = 1;
}
while (count != 1);
You already got an answer about the problem with predicate logic. But you can even more simplify with linq like:
var count = (new string[]{"1","2","3","4","5"}).Contains(Console.ReadLine()) ? 1 : 0;

If else Statment not working

Hi my If statement wont work for some reason I want it to say invalid if user goes below 0 or over 100 but every number i put in goes directly to my else statement doesn't even notice my if statement.
What am I doing wrong?
g:
Console.WriteLine("Enter Grade: ");
int grade = Convert.ToInt32(Console.Read());
if (grade < 0 || grade > 100)
{
Console.WriteLine("Input Valid");
Console.ReadLine();
}
else
{
Console.WriteLine("Input invalid");
Console.ReadLine();
}
goto g;
if/else is not a problem here. The way you're getting input from user is.
Use Console.ReadLine() instead of Console.Read():
int grade = Convert.ToInt32(Console.ReadLine());
Console.Read returns numeric representation (ACII code) of the first character from console, not the number you've typed itself.
Some changes you might need to do:
int grade = Convert.ToInt32(Console.ReadLine());
and change your condition to &&:
if (grade >= 0 && grade <= 100)
Change your read statement as follows:
int grade = Convert.ToInt32(Console.ReadLine());
Console.Read() returns the ASCII code that you typed, while Console.ReadLine() returns a string.

Categories