Reputation: 9
I have this C#
code here, and what I'm trying to do is that when I put a number with many digits the application crashes and I want it to not crash but I don't know what to do, I tried changing the .Parse
command but Idk which command to use instead. An example is that when I run the application I want to put a number like 564984894897987878
and I want the application to not crash, can someone help me, in this case, please? If you find a solution post it here including your code and my code too please and thank you?!
int num;
Console.Write("Please type your number here:");
num = Int32.Parse(Console.ReadLine());
if (num < 0)
Console.WriteLine("This is a negative number!");
if (num > 0)
Console.WriteLine("This number is a positive number");
Upvotes: 0
Views: 3465
Reputation: 1503859
If you want to represent an arbitrarily large integer, you should use BigInteger
.
If you use int
(aka System.Int32
) you'll be limited to a range of -2147483648 to 2147483647 inclusive.
If you use long
(aka System.Int64
) you'll be limited to a range of -9223372036854775808 to 9223372036854775807 inclusive.
Now it could be that long
is fine for you here - but a user would still be able to crash your app, or at least make it not work "as expected", pretty easily. With BigInteger
you should be fine for any integer value that your computer has enough memory to store.
Your code can be converted almost trivially to use BigInteger
- just use BigInteger.Parse
instead of Int32.Parse
, and then compare with BigInteger.Zero
. To improve the code further, beyond just handling large integers, you could use BigInteger.TryParse
to handle invalid inputs by gracefully reporting those to the user instead of crashing with a FormatException
.
Upvotes: 3
Reputation: 84
You can use TryParse:
Console.Write("Please type your number here:");
if(!Int32.TryParse(Console.ReadLine(), out num))
Console.WriteLine("Invalid number");
if (num < 0)
Console.WriteLine("This is a negative number!");
if (num > 0)
Console.WriteLine("This number is a positive number");
Upvotes: 0