检查用户输入是否为字符串

时间:2021-05-04 01:34:30

标签: c#

public int GetFuelToBurn(MarsLander ml)
        {
            int nFuel = 0;
            int fuelPoints = ml.GetFuelPoints();
            bool checker = false;
            
            while(checker == false)
            {
                Console.WriteLine("How many points of fuel would you like to burn?");
                Int32.TryParse(Console.ReadLine(), out nFuel);

                int currentFuel = fuelPoints;

                if (nFuel < 0)
                {
                    Console.WriteLine("You can't burn less than 0 points of fuel!");                  
                }
                if (nFuel % 1 != 0)
                {
                    Console.WriteLine("You need to type a whole number of fuel points to burn!");                    
                }
                if (currentFuel < nFuel)
                {
                    Console.WriteLine("You don't have {0} points of fuel!", nFuel);                    
                }
                else
                {
                    checker = true;
                    currentFuel = fuelPoints - nFuel;
                    ml.SetFuel(currentFuel);
                }
                Console.WriteLine("Just as a reminder, here's where the lander is: ");
                PrintLanderInfo(ml);
            }

            return nFuel;
          
        }

这是我拥有的当前代码,用户将输入一个值并将其存储到 nFuel 中,但是每当我输入像 hello 这样的单词时,它就会继续。我需要的是检查 nFuel 是否是一个数字,但我想不出有任何方法可以做到这一点,感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

<块引用>

我需要的是检查 nFuel 是否是一个数字,但我想不出有什么方法可以做到这一点

您的代码中已经有了它:

Int32.TryParse(Console.ReadLine(), out nFuel);

TryParse 返回一个布尔值。请从此处阅读有关如何使用它的更多信息并相应地修改您的代码:https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=net-5.0