How to use multi conditions in WHILE loop? [duplicate] - c#

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed last year.
I am trying to use OR condition in C# in WHILE loop, but it doesn't work :( if I do separate conditions without OR conditions then it works!
it works like this:
while (myAnswer.ToLower() != "yes")
{
Console.Write("Please write YES or NO!: ");
myAnswer = Console.ReadLine();
}
but if I try to add additional conditions, doesnt metter its AND or OR, it sends me to infinite loop. For example this doesnt work:
while ((myAnswer.ToLower() != "yes") || (myAnswer.ToLower() != "no"))
{
Console.Write("Please write YES or NO!: ");
myAnswer = Console.ReadLine();
}
any ideas?

If you want exit from your while if user writes YES or NO, your condition will be:
In other words, you repeat the question until the response will be YES or NO.
while ((myAnswer.ToLower() != "yes") && (myAnswer.ToLower() != "no"))
{
Console.Write("Please write YES or NO!: ");
myAnswer = Console.ReadLine();
}

Related

If statement multiple choice c#

string question1;
//Question 1
WriteLine("What is his favourite sport? ");
WriteLine("a) Soccer");
WriteLine("b) Basketball ");
WriteLine("c) Tennis ");
WriteLine("d) Football " );
Write("your answer is: ");
question1 = ReadLine();
if (question1 != "a" || question1 != "b" || question1 != "c")
Write("That is incorrect try again");
else
Write("that is correct");
No matter what letter I put it always gives me an incorrect try again, what am I doing wrong? Also would a while loop be better when trying to create a quiz game?
Those "or" (||) operators should almost certainly be "and" (&&) operators.
Think of what happens when you enter c, for example. Obviously, that will be c but it won't be a or b, so two of the sub-conditions will be true.
In fact, that's the case no matter which of a, b, or c that you enter (if you enter something else, all three will be true). And since an x || y || z is true if any of its sub-components is true, the expression as a whole is always true. The following table hopefully illustrates this:
Input
!= "a" (A)
!= "b" (B)
!= "c" (C)
A or B or C
a
False
True
True
True
b
True
False
True
True
c
True
True
False
True
d
True
True
True
True
other
True
True
True
True
In other words, unless question1 is some sort of "Schrodinger's variable" that can be all of a, b, and c at the same time, that if statement of yours will never be false.
However, if the subject's favourite sport is football, I'm not sure why you wouldn't just use the much simpler condition below:
if (question1 == "d") {
WriteLine("That is correct");
} else {
WriteLine("That is incorrect try again");
}
That approach (accepting the right answer) seems far easier than what your original code seems to be doing (rejecting all of the the wrong answers).
And, yes, a while loop probably would be better for a quiz scenario, something like the following would be a good start.
I've even added a rudimentary scoring system, because I get bored easily :-)
The points for a question reduce if you answer wrongly: two points for a correct answer first time, one point if you get it right second time, no points otherwise:
int score = 0; // Done once before ALL questions.
int awardPoints;
string answer;
awardPoints = 2; // Done before EACH question.
do {
// Output the question and get an answer.
WriteLine();
WriteLine("What is his favourite sport (x to exit)? ");
WriteLine(" a) Soccer");
WriteLine(" b) Basketball");
WriteLine(" c) Tennis");
WriteLine(" d) Football" );
Write("Your answer: ");
answer = ReadLine();
// Evaluate answer (d is correct here). An x answer
// will produce no output as it assumes you want to
// just exit.
if (answer == "d") {
score += awardPoints;
WriteLine("Correct, you earned {} points, now at {}",
awardPoints, score);
} else if (answer != "x") {
// Incorrect answer. Halve question points so
// user cannot simply keep trying without
// some penalty.
WriteLine("Incorrect, try again");
awardPoints = awardPoints / 2;
}
} while (answer != 'd' && answer != 'x');
// Here, either the correct answer or 'x' was
// given. If 'x', probably want to stop asking
// questions. Otherwise go on to next question.
Please, try this way.
void Main()
{
string question1 = "";
do
{
//Question 1
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("What is his favourite sport? ");
Console.WriteLine("a) Soccer");
Console.WriteLine("b) Basketball ");
Console.WriteLine("c) Tennis ");
Console.WriteLine("d) Football ");
Console.Write("your answer is: ");
question1 = Console.ReadLine();
Console.WriteLine(question1);
if (question1 == "a" || question1 == "b" || question1 == "c")
{
Console.Write("That is incorrect try again");
}
else
{
Console.Write("that is correct");
}
} while (question1 != "q");
}
When you use || operator, as soon as any condition is true, it stops processing rest of the cases and marks the statement as true.
The best way is, to test the correct answer and put rest of the cases in else block and mark them as 'incorrect'
if (question1 == 'correctOption')
{
System.Console.Write("That is correct.");
}
else
{
System.Console.Write("That is incorrect try again");
}
The runtime evaluates from left to right. In case of || it stops at the first true and returns true. If there is nothing which is true then it returns false.
In case of && it stop at the first false and returns false.
The readable code if to check for right answer and say correct and for all others display incorrect. This will also take care of user entering any other value other than "a","b,"c" as well like say "t"

I've created an infinite loop and I don't know why

namespace ChooseYourOwnAdventure
{
class Program
{
static void Main(string[] args)
{
/* THE MYSTERIOUS NOISE */
// Start by asking for the user's name:
Console.Write("What is your name?: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}! Welcome to our story.");
Console.WriteLine("It begins on a cold rainy night. You're sitting in
your room and hear a noise coming from down the hall. Do you go
investigate?");
Console.WriteLine("Type YES or NO");
string noiseChoice = Console.ReadLine();
string answer = noiseChoice.ToUpper();
if(answer == "NO")
{
Console.WriteLine("Not much of an adventure if we don't leave our
room. THE END");
return;
}
else if (answer == "YES")
{
Console.WriteLine("You walk into the hallway and see a light coming
from under a door down the hall. You walk towards it. Do you open it
or knock?");
}
else
{
Console.WriteLine("Command not recognized");
while((answer != "YES") || (answer != "NO"))
{
Console.WriteLine("Type YES or NO");
}
}
Console.WriteLine("Type OPEN or KNOCK");
string doorChoice = Console.ReadLine();
string answer2 = doorChoice.ToUpper();
I'm doing an exercise in Codecademy. I was creating my own adventure story before I did this so I thought this would be great practice to do anything that came to mind. I decided to do some error handling checks in case a user puts in some information which is where the else code block came from. I figured that if I used the while statement for any current and future errors the user introduces I could use the Console.WriteLine method to put the question forth until they type the specified values. Instead, the while I've created seems to have made an infinite loop within the compiler of "Type YES or NO". Can someone help me understand where I went wrong?
Every string is either not equal to "YES" or not equal to "NO" (e.g., if the input is "YES", it will not be equal to "NO", so the loop will continue). Instead of || (the logical "or" operator), you should use && (the logical "and" operator):
while((answer != "YES") && (answer != "NO"))
{
Console.WriteLine("Type YES or NO");
}
You are not re-assigning the answer variable in the while() loop you have made. #Mureinik is correct with why the loop is always active, but if they enter an input other than YES or NO then it will be infinite again. Try adding something like this:
while((answer != YES) && (answer != NO))
{
Console.WriteLine("Type YES or NO");
noiseChoice = Console.ReadLine();
answer = noiseChoice.ToUpper();
}
Because you were never updating the answer variable the while() loop's statement was always true, hence the infinite loop.

How to make sure an int doesn't crash an application when answered with a string [duplicate]

This question already has answers here:
Identify if a string is a number
(26 answers)
Closed 4 years ago.
I have a console app with an int variable. I need to read input from the user and be sure I can tell the user that they have entered an invalid answer if the input can't convert to an integer value.
How can I do this? Here is what I have so far:
class Program
{
static void Main(string[] args)
{
Start:
Console.WriteLine("Enter two numbers");
var input1 = Convert.ToInt32(Console.ReadLine());
var input2 = Convert.ToInt32(Console.ReadLine());
if (input1 + input2 == 3)
Console.WriteLine("");
else if (input1 + input2 == 10)
{
Console.WriteLine("");
}
else
Console.WriteLine("");
goto Start;
}
}
Convert.ToInt32(string) will throw exceptions, just as you mention, when the input cannot be parsed.
Instead, use int.TryParse(string, out var result).
In your code, it would be
if (!int.TryParse(Console.ReadLine(), out var input1 ||
!int.TryParse(Console.ReadLine(), out var input2))
{
Console.WriteLine("You did not enter integers.");
goto Start;
}
You can read more about the method in the .NET documentation
P.s. By the way, you should avoid using goto in your code. But that's another matter.
I would recommend using int.TryParse (documented here).
It will return false if the input is not an integer.
Ex:
int num1;
string input = Console.ReadLine();
if(!int.TryParse(input, out num1))
{
Console.WriteLine("that's not a valid integer");
}
use regular expression, Regex is best for c# to check number format. look at this:
Regex for numbers only

Trying to make quit sequence that only proceeds when correct input is given

i'm having trouble creating a loop that will request user input and if the input is not "Y" or "N" to re-prompt the user to input over and over until they give the correct input.
while (quitOrContinue != "Y"|"N")//cant use "Y"/"N" in the same line, how do I phrase this line?
Console.Write("\nWould you like to process another set of bowling scores?");
Console.WriteLine("\nPress 'Y' to process another set or 'N' to exit the program");
Console.Clear();// this needs to happen if the input to run again is "Y"
Well, for starters, you're not actually taking any input at all from the user. You can use Console.WriteLine to output whatever sort of instructions you want from the user, but you have to actually capture them somehow.
To get input, you'd have to use Console.Read(), and you'd have to use conditional blocks to check their input. You should wrap your code in a while loop that references a sentinel value:
bool userIsDone = false;
Console.Write("\nWould you like to process...");
while (!userIsDone)
{
string userInput = Console.ReadLine();
// ...
if (userInput == "Y")
{
// process another set here
Console.WriteLine("\nWould you like to process...");
}
else if (userInput == "N")
{
// exit your program
}
else
{
Console.WriteLine("That input is invalid.");
}
}
Also, about the code you have above - you should wrap the elements inside loops in { }, and the | is the bitwise OR, not logical or. Logical or (which I'm 99% you want in this situation) is ||, and logical and is &&.
Why not use a loop ?
string input = null;
while((input = Console.ReadLine()) != "Y" || input != "N")
{
Console.WriteLine("Invalid value, please try again:");
}
Here the expression (input = Console.ReadLine()) != "Y" || input != "N" will be evaluated before and each time after the loop runs. It basically reads a line from the input stream and assign it to input variable then checks if it's not Y or N it executes the loop body and evaluates the expression again and ask for input until the condition satisfies.You can use Console.Read method to read one charachter but it returns int so you need to cast it to char.

Why does it keep looping at Would You Like To Try Again?

Ok so I am trying to run this
static void Main(string[] args)
{
string ans;
bool Operation = false;
Console.WriteLine("Hello user, would you like to do maths today? Write yes or no.");
ans = Console.ReadLine();
ans.ToLower();
do
{
Console.WriteLine("Would you like to try again?");
string answerFinal = Console.ReadLine();
answerFinal.ToLower();
if (answerFinal == "yep")
{
Operation = true;
}
else
{
Operation = false;
}
}
while (Operation == true);
}
However, it keeps looping at Would You Like To Try Again if I keep pressing yes, any ideas why? I think it has to do with Try Catch, can someone tell me how to use them in this instance?
ans.ToLower();
doesn't modify anything in ans, it returns a copy of ans as lowercase. You need to do this:
ans = ans.ToLower();
For each time you use .ToLower(), like for answerFinal.
The problem is that you are using the same variable here
Console.WriteLine("Hello user, would you like to do maths today? Write yes or no.");
ans = Console.ReadLine();
ans.ToLower();
and here
Console.Clear();
Console.WriteLine("Please select from one of the operations!");
Console.WriteLine("Either write Multiplication, Division, Addition or Subtraction.");
ans = Console.ReadLine();
ans.ToLower();
So by the time the do-while starts again, the value in ans has already changed and isn't yes any longer so it just goes to the last statement. Change the second part of the code to
Console.Clear();
Console.WriteLine("Please select from one of the operations!");
Console.WriteLine("Either write Multiplication, Division, Addition or Subtraction.");
string answer = Console.ReadLine();
answer = answer.ToLower();
if (answer == "multiplication")
{
//other statements
Also, change
ans.ToLower();
to
ans = ans.ToLower();
and the same for the likes
You assign your ans variable to a bunch of different values in your loop, none of them being "yes". Then when you come back into the do loop again you fail the first condition statement if (ans == "yes"). This will be false, causing you to keep skipping over that block of code, landing you right back to the "Would you like to try again" line.

Categories

Resources