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"
Related
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.
I can't figure out how to check whether the input is a specific letter. I know how to check if it's a specific int/double but when it's a string I don't know what to do.
Any help would be greatly appreciated. I'm just trying to make a basic 3 question quiz that checks whether the user answers with the correct letter (a, b or c) and then adds that to the current score.
class Program
{
static void Main()
{
var a1 = "a";
var a2 = "b";
var a3 = "c";
var qa = 0;
while (qa != 3)
{
if (qa == 0)
{
Console.Write("What is the answer to question 1? ");
var entry1 = Console.Read();
if()
{
}
}
else if (qa == 1)
{
Console.Write("What is the answer to question 2? ");
Console.ReadLine();
}
else if (qa == 2)
{
Console.Write("What is the answer to question 3? ");
Console.ReadLine();
}
}
}
}
For example operator == can't be applied to strings
this is not true. It can be applied:
if(entry.ToString() == a1)
The documentation for the == operator tells us:
For the string type, == compares the values of the strings
another possibility would be to use the String.Equals method
if(entry.ToString().Equals(a1))
EDIT:
Looking closer at your code I realized that you are using Console.Read
which
Reads the next character from the standard input stream.
That means that it returns a char (and only 1).
I guess you want the entire line that the user types in. So you should use ReadLine instead. It returns a string and allows you for a direct comparison
string entry1 = Console.ReadLine();
if(entry == a1)
when you use var for the declaration of types the compiler infers the type and the error becomes obvious at a later stage. you cannot use the == operator on string and char . Read() returns a char so that's why you were not able to compare it in the first place
Note that in "Question 1" you wrote Console.Read(), (not Console.ReadLine()) which returns a char, not a string. So "==" cannot be applied to entry1 and a1 since entry1 will be a char while a1 is a string.
If you compare compatible variables, everything should be fine
string input1;
var input2 = "";
var input3 = 0;
// assign some input values, then compare
// strings
if (input1 == "a") // ok
{ }
if (input2 == "a") // ok
{ }
if (input3 == "a") // not ok, comparing int to string
{ }
// numbers
if (input1 == 1) // not ok, comparing string to int
{ }
if (input3 == 1) // ok
{ }
If you want to, you could try matching the ASCII value of the character by using Console.Read();. This would eliminate the need to press enter. If you were trying to match to uppercase A:
int input = Console.Read();
if (input == (int)char.GetNumericValue(A))
{
Console.WriteLine("True");
Console.Read();
}
else
{
Console.WriteLine("False");
Console.Read();
}
A quick question about C#. I have shown my code below, I cannot not work out why the loop will never close, the Do While loop should close when the user enters "A" or "B" etc, may sound like a stupid question I'm just starting C#
do
{
Console.WriteLine("What one would you like to buy? A B C or D");
a = Convert.ToChar(Console.ReadLine());
Console.WriteLine(a);
} while (a != 'A' || a != 'B' || a != 'C' || a != 'D');
You need to use "&&" instead of "||" since you want to exit when you DO NOT enter a, b, c, or d. Currently it will continue to run forever, since a is always either not 'a' or not 'b'.
Besides fixing your issue, I suggest you go for a safer and clearer approach, as your code throws an exception if the user enters more or less than one character, and also forces the user to press ENTER.
With this code the user just needs to press one key and it doesn't matter if it's uppercase or lowercase:
char a;
do
{
Console.WriteLine("Which one would you like to buy? A B C or D");
a = Char.ToUpper(Console.ReadKey().KeyChar);
Console.WriteLine();
} while (!"ABCD".Contains(a));
replace the OR condition by AND ( && ) !
Because if you type an 'A', (a == 'A'), then "a != 'B'" is true and the OR condition is TRUE...
You should use && in your condition.
You want your loop to stop when user either enters A or B in upper or lower case.In order words you want to continue only when what user entered is not A and not B(in upper or lower case)
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.
Im quite new to C# and am trying to write a super simple loop
while ((var_app_choice != "Exit") || (var_app_choice != "Test"))
{
//stuff
}
I have a console application where an end user will input a value
If this value is not equal (!=) to Exit OR Test then it should loop.
What am i doing wrong here?
Thanks
If you want to come out of the loop, when the User enters Exit or Test then you need the && operator not ||
while ((var_app_choice != "Exit") && (var_app_choice != "Test"))
{
var_app_choice = Console.ReadLine();
//stuff
}
I think you want and not or...
If the value of var_app_choice is "Test", then the first condition is true and the loop will execute. Similarly, if it's "Exit", then the second condition is true. In other words, you have an infinite loop...
Friend,
Consider I am having a data list as
List dataList = new List() { "Apple", "Microsoft", "exit", "Oracle", "Android" };
int i = 0;
while (dataList[i] != "exit" || dataList[i] != "test")
{
Console.WriteLine(dataList[i]);
i++;
}
You would expect that the ouput should be only Apple and Microsoft. When it encounters "exit" in index 2 it should stop.
What really happens(consider it is verifying "exit") is the first condition fails, which means NotEqualTo Operator works fine. The problem is your OR operator. Since "exit" not equals "test", the condition passed and it further enters into the loop.
Your data must not be equal to "exit" and also not equal to "test".
Think you got the problem. For your information, While(condn){} here you can mention any condition that outputs a boolean(true or false).
Thanks and Correct me if I am wrong.