2 回答
TA贡献1874条经验 获得超12个赞
用于TryParse检查输入是否为整数。然后,如果它是一个整数,对索引做任何你想做的事情。
else if (number == 5)
{
Console.Write("Student's index: ");
var success = int.TryParse(Console.ReadLine(), out int index1);
if (success)
{
//next logic here if the input is an integer
try
{
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
}
else
{
//do something when the input is not an integer
}
}
TA贡献1780条经验 获得超5个赞
您需要int.Parse在 try {} 块内移动您的行。只有这样,它才会在结构化异常处理的安全网中。然后,您可以针对 FormatException 添加第二个 catch {} 块,请参阅 Int32.Parse 文档以了解引发的异常。
else if (number == 5)
{
Console.Write("Student's index: ");
try
{
int index1 = int.Parse(Console.ReadLine());
customDataList.FindStudent(index1); //displays the element that has the specified index
}
catch (ArgumentOutOfRangeException)
{
Console.WriteLine("Please choose an index from 0 to 9!");
}
catch (FormatException)
{
Console.WriteLine("Error: Index must be a number.");
}
}
- 2 回答
- 0 关注
- 114 浏览
添加回答
举报