0
votes

I'm getting below exception while trying to print the last element in an array.

here is my code:

int[] nums = { 1, 2, 5, 7, 8 };

Console.WriteLine("first element is " + nums[0]);
int fe = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Last element is {0}" , nums[nums.Length - 1]);
int le = Convert.ToInt32(Console.ReadLine());

Exception:

first element is 1

Unhandled Exception: System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Convert.ToInt32(String value) at W2Resource.BasicExProb51.Main() in C:\Users\SudhaPraveen\Documents\Visual Studio 2017\Projects\CSharpPractice21DaysPlan\W2Resource\BasicExProb51.cs:line 16 Press any key to continue . . .

1
Debug and see what is returned by Console.ReadLine(). - JSteward
Hint: the exception is not happening when you think it does. - Sergey Kalinichenko
What is your input for Console.ReadLine ? - Anu Viswan
Look at your stacktrace, you find the method which caused the exception there, it starts with at.... Compare with the methods that you use and then you know that Convert.ToInt32 threw that exception. Why? Because what was in the console was not a valid integer - Tim Schmelter
Console.ReadLine() is not an integer which is why it is throwing an exception - koolkoda

1 Answers

2
votes

Your lines :

Console.WriteLine("first element is " + nums[0]);
Console.WriteLine("Last element is {0}" , nums[nums.Length - 1]);

Are both correct.

Your exception comes from user input in

Convert.ToInt32(Console.ReadLine());

As long as your user type a value that can be parsed as an integer, it works. Else it will raise the kind of exception you have seen.

If you don't use the input value, you could just replace it by :

Console.ReadKey();

It will make the program to "pause" until the user press a random key of the keyboard.

Else, if you need to use it, you have to validate the input before to use it. For example, I suggest you to check the behavior and usage of the int.TryParse() method.

Here's one answer to a question similar to yours : https://stackoverflow.com/a/45259920/461444 But it uses int.Parse() instead of int.TryParse() as suggested, which is not as good because it requires more code and raise a useless and perfectly avoidable exception.