我有以下代码。当我在控制台中键入0
时,我希望控制台显示"请重新输入您的年龄"但是永远不会输入if
块并退出程序。我做错了什么?
Console.WriteLine("Please entre your first name:");
Console.ReadLine();
Console.WriteLine("Please enter your last name:");
Console.ReadLine();
Console.WriteLine("Please type your age:");
Console.ReadLine();
int minAge = 18;
int maxAge = 68;
if (minAge < 18)
if (maxAge > 68)
Console.WriteLine("Please re-enter your age");
else
Console.WriteLine("Please choose f for female or m for male:");
答案 0 :(得分:2)
您没有将用户输入读入age
变量。执行此操作时,您需要考虑用户可能键入的非数字字符。您也没有将if
/ else
块包裹在花括号内,导致逻辑流程与您的意图不符。
以下代码将控制台输入读入年龄变量,使用int.TryParse拒绝不可解析的输入,并将minAge
和maxAge
值保留为constants。我们保留looping,直到用户输入有效数字作为年龄,如果他们没有资格继续,因为他们太年轻或太老,我们会退出:
const int minAge = 18;
const int maxAge = 68;
int age;
do
{
Console.WriteLine("Please type your age:");
} while (!int.TryParse(Console.ReadLine(), out age));
if (age < minAge || age > maxAge)
{
Console.WriteLine("I'm sorry, this application is for people aged {0} to {1} only", minAge, maxAge);
return; // or exit console app
}
Console.WriteLine("Please choose f for female or m for male:");
答案 1 :(得分:1)
您没有存储输入的年龄。因此,程序永远不会到达下一部分,因为您将minAge与minAge和maxAge与maxAge进行比较。也许你可以使用
int age = Convert.ToInt32(Console.Readline())
编辑:如果您不想要任何例外,可以使用
处理int age;
bool res = Int32.TryParse(Console.Readline(), out age);
if (!res)
Console.WriteLine("Please re-enter your age");
然后在下一部分中使用它们
if (age < minAge || age > maxAge )
Console.WriteLine("Please re-enter your age");
else
Console.WriteLine("Please choose f for female or m for male:");
答案 2 :(得分:0)
尝试以下可能会有所帮助,
int userage;
Console.WriteLine("Please type your age:");
userage=int.Parse(Console.ReadLine());
int minAge = 18;
int maxAge = 68;
if (userage>minAge || userage<maxAge)
Console.WriteLine("Age is not accepted");
else
Console.WriteLine("Your Age is {0}",userage.ToString());
//do what ever you want
//Console.WriteLine("Please choose f for female or m for male:");
Console.ReadLine();