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();
}
}
}