//Prompts user for their age
int age;
ApplicationUtilitiesinternal.DisplayDivider("Get Age");
Console.WriteLine("What is your age? ");
while (!int.TryParse(Console.ReadLine(), out age)) //Makes sure the user inputs a number for their age
Console.WriteLine("You did not enter a valid age - try again.");
age = InputUtilities.GetInput("Age");
我知道我需要解析变量,年龄,但我不知道该怎么做。我尝试了几种方法并在网上搜索了答案。就在我想我拥有它的时候......会弹出另一个错误。我知道这应该很简单。
编辑:
好的,我要在这里添加一些上下文。以下是我要打电话的内容:
class InputUtilities
{
internal static string GetInput(string inputType)
{
Console.WriteLine("Enter your " + inputType);
string strInput = Console.ReadLine();
return strInput;
}
}
我希望现在更有意义。
答案 0 :(得分:0)
回答你的实际问题:"我知道我需要解析变量,年龄,但我不知道该怎么做。",正如其他人所说,你是正在做。
我忽略了您的ApplicationUtilitiesinternal
和InputUtilities
课程,因为它们似乎与您的要求无关,以及InputUtilities.GetInput()
返回字符串这一事实并且您正尝试将其分配给int
(age
)。
我建议这段代码应该让事情更清楚:
Console.WriteLine("Please enter your age (1-120):");
int nAge;
while(true)
{
string sAge = Console.ReadLine();
if(!int.TryParse(sAge, out nAge))
{
Console.WriteLine("You did not enter a valid age - try again.");
continue;
}
if(nAge <= 0 || nAge > 120)
{
Console.WriteLine("Please enter an age between 1 and 120");
continue;
}
break;
}
// At this point, nAge will be a value between 1 and 120