I am writing a basic trivia program to help familiarize myself with C#. I’m in the early stages of development and ran into an issue that I’m having a hard time understanding. Here’s the code, followed by what I have tried thus far.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TriviaProject
{
internal class Program
{
static void Main(string[] args)
{
var q1 = "x";
int totalCorrect = 0;
int totalIncorrect = 0;
Console.WriteLine("Question 1: What is the answer?");
Console.WriteLine("A. Correct Answer");
Console.WriteLine("B. Incorrect Answer");
Console.WriteLine("C. Incorrect Answer");
while (q1 != "A" || q1 != "B" || q1 != "C")
{
q1 = Console.ReadLine();
switch (q1)
{
case "A":
Console.WriteLine("{0} is the correct Answer!", q1);
++totalCorrect;
break;
case "B":
Console.WriteLine("{0} is not correct.", q1);
++totalIncorrect;
break;
case "C":
Console.WriteLine("{0} is not correct.", q1);
++totalIncorrect;
break;
default:
Console.WriteLine("{0} is not a valid entry. A, B or C.", q1);
break;
}
}
Console.WriteLine("You got {0} correct and {1} incorrect. Your total score is: ", totalCorrect, totalIncorrect);
}
}
}
Desired Behavior
If the answer is A, then the totalCorrect tally should increase and be displayed. If the answer is B or C, then the totalIncorrect tally should increase and be displayed.
Tried Thus Far
- If I remove B and C from the WHILE statement, the program works as expect if I answer "A"
- To remedy the above scenario, I added B and C to the WHILE statement assuming I would see similar behavior when answering B and C
- When B and C are included in the While statement, I get the proper feedback (Correct or Incorrect) but the loop continues regardless of what I enter (program never moves on to results)
I have also tried different combinations of using CONTINUE instead of BREAK.
If anyone could explain this behavior, it would be greatly appreciated.
>Solution :
Your while loop is, logically, while (true).
q1 != "A"
That’s false if q1 is A, otherwise it’s true
q1 != "B"
That’s false if q1 is B, otherwise it’s true
Since A is not B, there’s no way both of those statements can be false at the same time, so you have
- A) false || true
- B) true || false
- other) true || true
Since true-or-anything is true, your condition is just true.