简体   繁体   English

我如何在 c# 中实现直到循环

[英]How do i implement an until loop in c#

I am making a simple Higher, Lower game and I want the game to continue until the right number is guessed or if the guesser wants to restart.我正在制作一个简单的更高、更低的游戏,我希望游戏继续进行,直到猜到正确的数字或猜者想要重新开始。 What loop do I use and how would I implement it我使用什么循环以及如何实现它

my code is我的代码是

Random RandomNumber = new Random();
int RandomNumber2 = RandomNumber.Next(1, 5);
//Console.WriteLine(RandomNumber2);

//want to insert loop here and it should end when the third else if is done

Console.WriteLine("Make Your Guess Now");
string UserInput = Console.ReadLine();
int UserInput2 = Convert.ToInt32(UserInput);

if (UserInput2 > RandomNumber2)
{
    Console.WriteLine("Your Number is to high");
}
else if (UserInput2 < RandomNumber2)
{
    Console.WriteLine("Your Number is too small");
}
else if (UserInput2 == RandomNumber2)
{
    Console.WriteLine("Congrats on guessing the right number");
}

The standard way to do it is to use a do while loop (C# Reference) .执行此操作的标准方法是使用do while 循环(C# 参考)

Bute here, you can use an infinite loop and exit from it using a break statement.但是在这里,您可以使用无限循环并使用break语句退出它。 This allows you to break out of the loop from a condition tested inside the loop这允许您从循环内测试的条件中跳出循环

...
Console.WriteLine("Make Your Guess Now");
while (true) {
    string UserInput = Console.ReadLine();
    int UserInput2 = Convert.ToInt32(UserInput);

    if (UserInput2 > RandomNumber2)
    {
        Console.WriteLine("Your Number is too high. Make another guess");
    }
    else if (UserInput2 < RandomNumber2)
    {
        Console.WriteLine("Your Number is too small. Make another guess");
    }
    else
    {
        Console.WriteLine("Congrats on guessing the right number");
        break;
    }
}

Note that there is no need to test for UserInput2 == RandomNumber2 in the last else, since the other cases have been treated above, this is the only possibility remaining.请注意,不需要在最后一个 else 中测试UserInput2 == RandomNumber2 ,因为上面已经处理了其他情况,这是唯一剩下的可能性。 Note that an else-part is executed when the if-part is not executed and only then.请注意,当 if-part 未执行时才执行 else-part 并且仅在那时执行。

Like said It think the best solution is就像说它认为最好的解决方案是

Do
{
  --if here
} While (userinput2==randomnumber2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM