2 回答

TA貢獻(xiàn)1874條經(jīng)驗(yàn) 獲得超12個(gè)贊
用于TryParse檢查輸入是否為整數(shù)。然后,如果它是一個(gè)整數(shù),對索引做任何你想做的事情。
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貢獻(xiàn)1780條經(jīng)驗(yàn) 獲得超5個(gè)贊
您需要int.Parse在 try {} 塊內(nèi)移動(dòng)您的行。只有這樣,它才會(huì)在結(jié)構(gòu)化異常處理的安全網(wǎng)中。然后,您可以針對 FormatException 添加第二個(gè) catch {} 塊,請參閱 Int32.Parse 文檔以了解引發(fā)的異常。
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 關(guān)注
- 137 瀏覽
添加回答
舉報(bào)