Reputation: 31
I want the code to continue running until a user guesses the correct answer. However the code runs something else infinitely.
public class Quiz{
//Make various questions with correct/incorrect options
/*
* Suggestion
* Question 1
* How old was the first king of sweden when he passed?
* Options1
* 40
* 60
* 80
*/
public static int correctAnswer = 40;
public static int guess = Convert.ToInt32(Console.ReadLine());
public static void Guess(){
System.Console.WriteLine("How old was the 1st King of Sweden\n");
System.Console.WriteLine("when he passed away?");
while(guess != correctAnswer){
if(guess == correctAnswer){
System.Console.WriteLine("Correct answer. Congratulations.");
} else{
System.Console.WriteLine("Try again.");
}
}
}
}
I tried changing from do-while to while but that did not help.
Upvotes: -2
Views: 93
Reputation: 62
If i understand correctly you say it's loop over many times until it crush. I guess it could be because you don't reasign any value to guess after you enter the loop so the flow chart of you program is like:
so what i suggest is first to think on the flow of the program what you want it to do simple as to write it done without any code then code it you would find it very helpful when you try to correct issues youy encounter
second i suggest to edit the loop to check only when the answer is not correct try to think what is the flow chart i used
public static void Guess()
{
//this /n gone add 2 lines down
System.Console.WriteLine("How old was the 1st King of Sweden\n");
System.Console.WriteLine("when he passed away?");
int guess = Convert.ToInt32(Console.ReadLine());
while(guess != correctAnswer)
{
System.Console.WriteLine("Try again.");
guess = Convert.ToInt32(Console.ReadLine());
}
// when we reach the end of the loo, user gave a correct answer
System.Console.WriteLine("Correct answer. Congratulations.");
}
Upvotes: 0
Reputation: 37095
you never assign anything to guess
after it was set the very first time. You need to re-assign guess
in every iteration:
public static int correctAnswer = 40;
public static void Guess()
{
System.Console.WriteLine("How old was the 1st King of Sweden\n");
System.Console.WriteLine("when he passed away?");
var guess = Convert.ToInt32(Console.ReadLine());
while(guess != correctAnswer)
{
System.Console.WriteLine("Try again.");
guess = Convert.ToInt32(Console.ReadLine());
}
// when we reach the end of the loo, user gave a correct answer
System.Console.WriteLine("Correct answer. Congratulations.");
}
Upvotes: 2