【发布时间】:2021-06-09 15:28:01
【问题描述】:
谁能告诉我为什么当用户输入无效格式的数据时,第一次尝试捕获没有显示错误消息,即输入整数而不是字符串。如果我输入数字而不是字母,程序只会接受它并继续前进。 另一个 try catch for age 工作正常。
public void add_passenger()
{
// Defining variables for name and age to be input
string name;
int age;
//Show message on a clean, new screen
Console.Clear();
Console.WriteLine("==> Welcome aboard <==");
Console.WriteLine(" Please follow instructions to add yourself as a passenger ");
Console.WriteLine("");
// Ask user to input name
while (true)
{
Console.WriteLine(" Your name: ");
//Try and catch in case the user inputs wrong format
try
{
name = Console.ReadLine();
break;
}
catch //This doesn't work
{
Console.WriteLine(" Wrong input format. Please try again and input a rider.");
continue;
}
}
// Ask user to input age
while (true)
{
Console.WriteLine(" Your age: ");
//Try and catch in case the user inputs wrong format
try
{
age = Convert.ToInt32(Console.ReadLine());
break;
}
catch
{
Console.WriteLine(" Wrong input format. Please write an integer.");
continue;
}
}
// Search the array for an empty slot to input the new passenger into
for (int i = 0; i < passengers.Length - 1; i++)
{
if (passengers[i] == null)
{
passengers[i] = new Passagerare(name, age);
break;
}
else
{
continue;
}
}
Console.WriteLine("");
Console.WriteLine(" You have now boarded the bus. Welcome aboard!" );
Console.ReadKey(true);
}
【问题讨论】:
-
代码行……
name = Console.ReadLine();……将接受任何“包括”数字的值。数字也可以是有效的string。由于代码正在读入string变量name,因此所有值都被接受。name的什么值会被视为无效值? -
感谢您的评论。我希望名称只能存储字母或字母,而不是数字。我想我需要为此做一些研究