扫描仪在while循环中

时间:2019-07-19 08:49:24

标签: java c# if-statement while-loop

private int scanner = Convert.ToInt32(Console.ReadLine());
public void Play()
        {
            while (true)
            {
                if (scanner > theNumber)
                {
                    Console.WriteLine("your number is too big");
                } else 
                if (scanner < theNumber)
                {
                    Console.WriteLine("your number is too big");
                }  else
                {
                    Console.WriteLine("you got it");
                    break;
                }
            }
        }

这是一个简单的游戏,我需要通过一组if语句来迭代相同的数字。在Java中,他们使用

int x;

x = scn.nextInt();

我可以在C#中使用什么?没有扫描仪。

C# equivalent to Java's scn.nextInt( )这篇文章没有解释如何用C#制作扫描仪。它仅说明了如何解析用户输入以使其仅成为整数

1 个答案:

答案 0 :(得分:1)

让我们为其提取一种方法ReadInteger)。请注意,我们使用int.TryParse代替Convert.ToInt32,因为用户输入不必要有效整数

 private static int ReadInteger(String title = null) 
 {
     if (!string.IsNullOrWhiteSpace(title))
         Console.WriteLine(title);

     while (true) 
     {
         if (int.TryParse(Console.ReadLine(), out int result))
             return result;

         Console.WriteLine("Sorry, the input is not a valid integer, try again");
      } 
 }

然后我们可以使用它:

    public void Play()
    {
        while (true)
        {
            // We should re-read value after each attempt
            int value = ReadInteger();

            if (value > theNumber)
            {
                Console.WriteLine("your number is too big");
            } 
            else if (value < theNumber)
            {
                Console.WriteLine("your number is too big");
            }  
            else
            {
                Console.WriteLine("you got it");
                break;
            }
        }
    }
相关问题