我想要一些关于用户整数输入的快速帮助。如果我使用字符串我没有问题,但当我尝试将其转换为int数时,程序崩溃。任何快速修复?
string a = Console.ReadLine();
int age = Convert.ToInt32(a);
Console.WriteLine("What is your age?" + age);
if ((age >= 1) && (age <= 6))
{
Console.WriteLine("you are in Preschool");
}
else if ((age == 7) && (age >= 13))
{
Console.WriteLine("you are in Elementary School");
}
else if ((age == 14) && (age >= 18))
{
Console.WriteLine("You are in High School");
}
else if ((age == 19) && (age >= 26))
{
Console.WriteLine("You are probably in College");
}
else
{
Console.WriteLine("you probaby have graduated already");
}
答案 0 :(得分:0)
您的代码中的第一个更改应该是正确解析整数值
int age = -1;
if(int.TryParse(a,out age))
{
//rest of code
}
(适用问题)强> 其他变化是你的条件
else if ((age == 7) && (age >= 13))
这不会像您进行&&
操作一样有效,并说age==7 && age>=13
这意味着年龄必须是7岁,必须大于13岁
适用于所有条件
else if ((age == 7) && (age >= 13))
{
Console.WriteLine("you are in Elementary School");
}
else if ((age == 14) && (age >= 18))
{
Console.WriteLine("You are in High School");
}
else if ((age == 19) && (age >= 26))
{
Console.WriteLine("You are probably in College");
}
似乎应该(解决方案)
else if ((age >= 7) && (age <= 13))
{
Console.WriteLine("you are in Elementary School");
}
else if ((age >= 14) && (age <= 18))
{
Console.WriteLine("You are in High School");
}
else if ((age >= 19) && (age <= 26))
{
Console.WriteLine("You are probably in College");
}
完整的解决方案是
Console.WriteLine("What is your age?");
string a = Console.ReadLine();
int age = -1;
if(int.TryParse(a,out age))
{
Console.WriteLine("your age is : " + age);
if(age < 1)
{
Console.WriteLine("Input value should be greater then 0");
}
else if ((age >= 1) && (age <= 6))
{
Console.WriteLine("you are in Preschool");
}
else if ((age >= 7) && (age <= 13))
{
Console.WriteLine("you are in Elementary School");
}
else if ((age >= 14) && (age <= 18))
{
Console.WriteLine("You are in High School");
}
else if ((age >= 19) && (age <= 26))
{
Console.WriteLine("You are probably in College");
}
else
{
Console.WriteLine("you probaby have graduated already");
}
}
else
{
Console.WriteLine("InCorrect input value");
}
答案 1 :(得分:0)
解决问题的另一种方法是使用少量代码。对我来说,如果不那么复杂的if语句会更容易阅读。由于年龄间隔,Switch语句对这种情况没有帮助。它只会变得更复杂。
string text = String.Empty;
int age;
Console.WriteLine("What is your age?");
if (int.TryParse(Console.ReadLine(), out age))
{
if (age > 26)
text = "You probaby have graduated already.";
else if (age < 1)
text = "You probaby not started Preschool.";
else if (age < 7)
text = "You are in Preschool.";
else if (age < 14)
text = "You are in Elementary School.";
else if (age < 19)
text = "You are in High School.";
else
text = "You are probably in College.";
Console.WriteLine(text);
}
}
答案 2 :(得分:-4)
试试这个: - 如果条件为false,请将其更改为如下所示。
$('#modal2').modal('open');