【问题标题】:scanner in while loop [duplicate]while循环中的扫描仪[重复]
【发布时间】:2019-11-28 05:36:35
【问题描述】:
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# 制作扫描仪。它只解释了如何解析用户的输入,使其仅是整数

【问题讨论】:

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


【解决方案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;
            }
        }
    }

【讨论】:

  • 谢谢。这是我一直在努力的部分:if (int.TryParse(Console.ReadLine(), out int result)) return result;
  • @feedthemachine:我明白了;与c#不同,Java没有refout参数
猜你喜欢
  • 1970-01-01
  • 2018-05-03
  • 1970-01-01
  • 2013-11-25
  • 2016-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-30
相关资源
最近更新 更多