0

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 . . .

Ash0214
  • 25
  • 1
  • 3
  • Debug and see what is returned by `Console.ReadLine()`. – JSteward Dec 31 '18 at 16:27
  • 3
    Hint: the exception is not happening when you think it does. – Sergey Kalinichenko Dec 31 '18 at 16:28
  • 2
    What is your input for Console.ReadLine ? – Anu Viswan Dec 31 '18 at 16:28
  • 1
    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 Dec 31 '18 at 16:29
  • Console.ReadLine() is not an integer which is why it is throwing an exception – koolkoda Dec 31 '18 at 16:40
  • You are using Console.ReadLine() to wait for user input, but you are trying to convert whatever the user typed before the enter into a number. If the user only hitted enter, that is not a valid number. – Cleptus Dec 31 '18 at 16:41

1 Answers1

2

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.

AFract
  • 8,868
  • 6
  • 48
  • 70