我希望代码继续运行,直到用户猜出正确答案。 然而,代码无限地运行其他东西。
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.");
}
}
}
}
我尝试将 do-while 更改为 while,但这没有帮助。
在第一次设置后,你永远不会给
guess
分配任何东西。您需要在每次迭代中重新分配 guess
:
public static int correctAnswer = 40;
public static int guess;
public static void Guess()
{
System.Console.WriteLine("How old was the 1st King of Sweden\n");
System.Console.WriteLine("when he passed away?");
guess = Convert.ToInt32(Console.ReadLine());
while(guess != correctAnswer)
{
System.Console.WriteLine("Try again.");
guess = Convert.ToInt32(Console.ReadLine());
}
}