-1

I am working on a console application that's a simple calculator in C# and I want to check if the user has entered a string instead of a number/decimal. Instead I get a System.Format Exception which breaks the program. I'm unsure how to tell the program not to break if it sees string characters. I've used do while loops as a way to re-prompt the user if they enter a negative number or any other invalid value.

Here's my code:

using System;


namespace Calc
{
    public class Calc
    {
        public static void Main()
        {

        ///Declare variables
        double p,r,y;
        string input1, input2, input3;



        ///Prompt user to reenter value if the input is illegal
        do
        {
            ///Prompt the user for the principal
            Console.Write("Enter the principal: ");
            input1 = Console.ReadLine();
            p = double.Parse(input1);
        } while(p < 0 ); 


        ///Prompt the user for the rate
        Console.Write("Enter the rate: ");
        input2 = Console.ReadLine();
        r = double.Parse(input2);

        ///Prompt user to reenter value if the input is illegal
        do 
        {
            ///Prompt the user for the rate
            Console.Write("Enter the rate: ");
            input2 = Console.ReadLine();
            r = double.Parse(input2);

        } while(r < 0);



        ///Prompt user to reenter value if the input is illegal
        do 
        {
            ///Prompt the user for the number of years
            Console.Write("Enter the number of years: ");
            input3 = Console.ReadLine();
            y = double.Parse(input3);
        } while (y < 0);

        ///Calculate the user input using the mortgage rate formula
        double p1 = (r / 1200.0);
        double m = y * 12;
        double nm = 0 - m;
        double month = p * p1 / (1 - System.Math.Pow((1 + p1), nm));



        //Output the result of the monthly payment
        Console.WriteLine(String.Format("The amount of the monthly payment is: {0}{1:0.00}", "$", month));
        Console.WriteLine();
        Console.WriteLine("Press Enter to end the calculator program. . .");
        Console.Read();
    }
}
}
user2101463
  • 343
  • 1
  • 4
  • 14
  • See marked duplicate. Exact same advice applies whether you are dealing with `int`, `double`, `DateTime`, or any other parseable type. See also discussion at http://stackoverflow.com/questions/531397/handling-exceptions-vs-preventing-them-from-occuring-in-the-first-place-c-sha – Peter Duniho Apr 01 '17 at 18:52
  • Other relevant and useful posts include http://stackoverflow.com/questions/150114/parsing-performance-if-tryparse-try-catch, http://stackoverflow.com/questions/12768625/cannot-implicitly-convert-type-string-to-double-issue, and http://stackoverflow.com/questions/8122604/check-if-string-can-be-converted-to-a-given-type-in-c-sharp – Peter Duniho Apr 01 '17 at 18:54

2 Answers2

3

You can use TryParse which returns a bool to tell if the conversion was successful:

bool IsValid = double.TryParse(input2,out r);

Now you can check if IsValid returns true then it is a valid value coming, otherwise you can prompt user to re-enter:

    bool IsValid = false;
    ///Prompt user to reenter value if the input is illegal
    do 
    {
        ///Prompt the user for the rate
        Console.Write("Enter the rate: ");
        input2 = Console.ReadLine();
        IsValid = double.TryParse(input2, out r);

    } while(!IsValid && r < 0);
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

Use Double.TryParse

Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.

this way, you can get if the number is convertible before using it...

McKabue
  • 2,076
  • 1
  • 19
  • 34