0

I get "Unhandled Exception: System.FormatException: Input string was not in a correct format." but actually I catch the Exception with 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!");
        }
    }
}

When the input is string it goes to the else block(so it catches the exception), but when the input is an integer I get Unhandled Exception: System.FormatException: Input string was not in a correct format.

1
  • 4
    The exception is probably thrown by Console.Write("Enter number {}: ", counter); Commented Nov 28, 2013 at 20:23

3 Answers 3

3

The line

Console.Write("Enter number {}: ", counter);

will throw an exception, you should change it to

Console.Write("Enter number {0}: ", counter);
Sign up to request clarification or add additional context in comments.

1 Comment

Obviously.. How I could not have seen that! Very stupid mistake.. Thank you very much!
1

It's your format string that is causing the error message. Put an index between the brackets:

Console.Write("Enter number {0}: ", counter);

Comments

0

In addition to the Console.Write error already fixed by previous posters, you will also get a System.InvalidOperationException here if the user enters only strings because numbers list will be empty.

minNum = numbers.Max();
maxNum = numbers.Min();

1 Comment

Yes you are right I put minNum = numbers.Max(); maxNum = numbers.Min(); in the else block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.