C#.NET While loop not exiting - c#

This is a short function to check and make user write uppercase Y or N .I dont know why but even if the user enter upper case Y or N , still then the loop does not exit. Any help please?
static char GetUpperCaseYN()
{
char choice='y';
Console.WriteLine("Calculate Another? Y/N ");
choice = char.Parse(Console.ReadLine());
while (choice != 'Y' || choice != 'N')
{
Console.WriteLine("Invalid Response.Please enter Y or N");
choice = char.Parse(Console.ReadLine());
}
return choice;
}

Use && not ||; they can't both be false with one character :)

Related

C# How can I make an exception to allow only numbers?

Here is my Code
Console.WriteLine("Do you want to: 1. play against an Ai or 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
int userInput = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\n");
if (userInput == 1)
{
// Player
Player player = new Player();
I tried to make an try catch block but then I always got a porblem with userInput in my if statement. I want a try .. catch block to make sure, if the user enters a char or somethingelse (+,~,#,...) they get an error message and can enter something new.
I suggest using loop and if instead of catching exceptions (exceptions have been designed for exceptional situations which are not the case - we should validate user input only):
int userInput = -1;
// Keep on asking user until valid input is provided
while (true) {
Console.WriteLine("Do you want to:");
Console.WriteLine(" 1. play against an Ai or ");
Console.WriteLine(" 2. let two Ai´s play aigainst each other?");
Console.WriteLine("Please choose one option!");
// Trim() - let's be nice and tolerate leading and trailing spaces
string input = Console.ReadLine().Trim();
if (input == "1" || input == "2") {
userInput = int.Parse(input);
break;
}
Console.WriteLine("Sorry, invalid option. Please, try again.");
}

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.

Testing Values For Multiple Conditions in 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)

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