仅允许插入数字并将小时数转换为分钟以计算黄金/分钟 – 更新

我有一个应用程序来计算每分钟养殖的黄金。 我想制作一个错误报告,不允许您在控制台输入中插入任何文本,您可以在其中插入时间和金币(如下面的代码所示)并显示一些错误消息,如果您这样做并让您重做插入(某种循环或if / else的东西……)希望我清楚自己,你是我的新手…所以我希望你理解。 这是我的代码到目前为止:——————————- //////////
有问题的更新,因为我不想为相同的代码提出新问题:
我如何在这段代码中将我的小时转换为分钟,1.2小时的浮点计算将计算为72分钟而不是80分钟。(我在下面的代码中将注释放在问题所在的代码中)

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace YourGold { class Program { static void Main(string[] args) { Console.WriteLine("Welcome to YourGold App! \n------------------------"); Console.WriteLine("Inesrt your gold: "); int gold = int.Parse(Console.ReadLine()); Console.WriteLine("Your gold is : " + gold); Console.WriteLine("Inesrt your time(In Hours) played: "); float hours = float.Parse(Console.ReadLine()); int minutes = 60; float time = (float)hours * minutes; // Here the calculation are wrong... Console.WriteLine("Your total time playd is : " + time + " minutes"); float goldMin = gold / time; Console.WriteLine("Your gold per minute is : " + goldMin); Console.WriteLine("The application has ended, press any key to end this app. \nThank you for using it."); Console.ReadLine(); } } } 

谢谢!

您可以使用int.TryParse而不是使用int.Parse ,并打印消息:

 int gold; while(!int.TryParse(Console.ReadLine(), out gold)) { Console.WriteLine("Please enter a valid number for gold."); Console.WriteLine("Inesrt your gold: "); } 

这允许您正确地重新提示和处理错误。

在控制台应用程序中,您无法控制文本输入(没有要处理的按键事件)。

这可能是一个解决方案

  Console.WriteLine("Inesrt your gold: "); int gold; while(!int.TryParse(Console.ReadLine(),out gold)){ Console.WriteLine("Please provide a valid gold value"); } Console.WriteLine("Your gold is : " + gold);