A 32-bit int
cannot hold 10 full digits, its max value is 2,147,483,647
.
In other words, int.Parse
detects that your int would overflow, and gives that error.
题
I implemented the following method in c#, to check if the user-entered number is a 10 digit number or not. It is working fine for an input number of upto 10 digits. But, when I enter a number of greater than 10 digits it prints Given string does not represent a number instead of The length of the Contact No. is not 10
I know that I can do the same thing using regex-matching, but I just want to do it by using throwing exceptions. Any help is appreciated.
public static bool CheckContactNo(string ContactNo)
{
try
{
int Number = int.Parse(ContactNo);
int IsZero = ContactNo.Length == 10 ? 1 : 0;
//Console.WriteLine("{0}",IsZero);
int somenum = 1/ IsZero;
return true;
}
catch(DivideByZeroException)
{
Console.WriteLine("The length of the Contact No. is not 10");
return false;
}
catch (Exception)
{
Console.WriteLine("Given string does not represent a number");
return false;
}
}
解决方案
A 32-bit int
cannot hold 10 full digits, its max value is 2,147,483,647
.
In other words, int.Parse
detects that your int would overflow, and gives that error.
其他提示
Int32.MaxValue is 2,147,483,647 . You won't be able to parse numbers larger than int.maxvalue.
In addition to Joachim's answer (where the solution is to use Int64
), I would also not use exceptions (like DivZero) to control flow in that way, instead prefer to use validations like TryParse
to determine whether the value is numeric:
if (contactNo.Length != 10)
{
Console.WriteLine("The length of the Contact No. is not 10");
}
else
{
long contactLong;
if (Int64.TryParse(ContactNo, out contactLong)
{
return true;
}
else
{
Console.WriteLine("Given string does not represent a number");
}
}
return false;
You can use Int64
instead of int
This(2,147,483,647) is the maximum value for Int32 so int.Parse internally checks for this You could use Int64.Parse