一直问,直到输入是正确的

本文关键字:输入 一直 | 更新日期: 2023-09-27 18:18:47

我试图创建一个小游戏与3个不同的选项,但我不知道如何在代码中编写:如果答案不是1,2,3,继续问这个问题,直到输入是1,2,3。

        Console.WriteLine("What do you want to do?");
        Console.WriteLine("1. Eat");
        Console.WriteLine("2. Drink");
        Console.WriteLine("3. Play");
        string answer = Console.ReadLine();
        if (answer == "1")
        {
            Console.WriteLine("you picked number 1");
        }
        if (answer == "2")
        {
            Console.WriteLine("You picked number 2");
        }
        if (answer == "3")
        {
            Console.WriteLine("You picked number 3");
        }
        // if answer isn't 1,2 or 3, keep asking the question untill the input is correct.

一直问,直到输入是正确的

  var answer="";
  while(true)
  {
    Console.WriteLine("What do you want to do?");
    Console.WriteLine("1. Eat");
    Console.WriteLine("2. Drink");
    Console.WriteLine("3. Play");
    answer = Console.ReadLine();
    if (answer == "1")
    {
        Console.WriteLine("you picked number 1");
        break;
    }
    if (answer == "2")
    {
        Console.WriteLine("You picked number 2");
        break;
    }
    if (answer == "3")
    {
        Console.WriteLine("You picked number 3");
        break;
    }
  }

  var answer="";
  while(answer!="1" && answer!="2" && answer!="3")
  {
    Console.WriteLine("What do you want to do?");
    Console.WriteLine("1. Eat");
    Console.WriteLine("2. Drink");
    Console.WriteLine("3. Play");
    answer = Console.ReadLine();
    if (answer == "1")
    {
        Console.WriteLine("you picked number 1");
    }
    if (answer == "2")
    {
        Console.WriteLine("You picked number 2");
    }
    if (answer == "3")
    {
        Console.WriteLine("You picked number 3");
    }
  }

  var answer="";
  var validanswers = new [] {"1","2","3"};
  while(!validanswers.Contains(answer))
  {
    Console.WriteLine("What do you want to do?");
    Console.WriteLine("1. Eat");
    Console.WriteLine("2. Drink");
    Console.WriteLine("3. Play");
    answer = Console.ReadLine();
    if (answer == "1")
    {
        Console.WriteLine("you picked number 1");
    }
    if (answer == "2")
    {
        Console.WriteLine("You picked number 2");
    }
    if (answer == "3")
    {
        Console.WriteLine("You picked number 3");
    }
  }

类似于

string answer = String.Empty;
do
{
    Console.WriteLine("What do you want to do?");
    Console.WriteLine("1. Eat");
    Console.WriteLine("2. Drink");
    Console.WriteLine("3. Play");
    answer = Console.ReadLine();
} while (answer != "1" && answer != "2" && answer != "3");
//handle answer here