c#如何解析变量?
本文关键字:变量 何解析 | 更新日期: 2023-09-27 18:12:03
//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");
我知道我需要解析变量age,但我不确定如何做到这一点。我尝试了几种方法,并在网上搜索答案。就在我以为自己成功的时候…会弹出另一个错误。我知道这应该很简单。
编辑:好的,我将在这里添加一些上下文。下面是我从
调用的代码class InputUtilities
{
internal static string GetInput(string inputType)
{
Console.WriteLine("Enter your " + inputType);
string strInput = Console.ReadLine();
return strInput;
}
}
我希望现在这更有意义。
要回答您的实际问题:"我知道我需要解析变量,年龄,但我不确定如何做到这一点。"正如其他人已经说过的那样,您正在这样做。
我忽略了您的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