我得到「未處理的異常:System.FormatException:輸入字符串的格式不正確。」但實際上我用TryParse捕獲了Exception。C#爲什麼我得到「未處理的異常:System.FormatException:輸入字符串的格式不正確。」當我使用TryParse?
using System;
using System.Linq;
using System.Collections.Generic;
class MinAndMax
{
static void Main()
{
// Task 3 - Write a program that reads from the console
// a sequence of N integer numbers and returns the minimal
// and maximal of them.
int n;
double num = 0, counter = 0, minNum = 0, maxNum = 0;
List<double> numbers = new List<double>();
Console.Write("How many numbers will you enter: ");
bool isNum = int.TryParse(Console.ReadLine(), out n);
if (isNum)
{
for (counter = 1; counter <= n; counter++)
{
Console.Write("Enter number {}: ", counter);
bool isValid = double.TryParse(Console.ReadLine(), out num);
if (isValid == false)
{
Console.WriteLine("Invalid input!");
}
else
{
numbers.Add(num);
}
}
minNum = numbers.Max();
maxNum = numbers.Min();
Console.WriteLine("The maximal of the numbers is: " + maxNum);
Console.WriteLine("The minimal of the numbers is: " + minNum);
}
else
{
Console.WriteLine("Invalid input!");
}
}
}
當輸入字符串它進入else塊(所以它捕獲該異常),但是當輸入是一個整數,我得到未處理的異常:System.FormatException:輸入字符串的不正確的格式。
的異常可能是由'Console.Write拋出( 「輸入號碼{}」,計數器);' – Lee
@Lee你是對的:) –