用户输入字符而不是双精度时的错误处理

时间:2015-04-13 21:52:58

标签: c# .net error-handling double

我做了一个简单的应用程序,根据本金年数和利率计算贷款的每月付款。如果用户输入的是字符而不是双精度,则程序崩溃。当有人插入信件时,如何创建一条说“请输入有效号码”的信息?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HW1Udeshi
{
    class Program
    {
        static void Main(string[] args)
        {

            bool Continue; 
            while (true) 
            {
                //initialize variables

                double r, yrs, m, p;
                string input, output;

                //principle amount
                Console.Write("Enter a Principle Amount: ");
                input = Console.ReadLine();
                //Int32.Parse
                p = double.Parse(input);

                //Number of years 
                Console.Write("Enter Number of Years: ");
                input = Console.ReadLine();
                //Int32.Parse
                yrs = double.Parse(input);

                //Interest Rate
                Console.Write("Enter Interest rate: ");
                input = Console.ReadLine();
                //Int32.Parse
                r = double.Parse(input);

                //monthly payment  formula:
                m = (p * r / 1200.0) / (1 - Math.Pow((1.0 + r / 1200.0),(-12 * yrs)));

                //Round two decimal pts 
                m = Math.Round(m,2);

                //output
                output = m.ToString();
                Console.WriteLine("Monthly payment is " + m + ".");
                Console.ReadLine();

                Console.WriteLine("Do you want to Continue y/n?");
                if (Console.ReadLine() == "y")
                {
                    Continue = true;
                }
                else
                {
                    Environment.Exit(0);
                }

            } 

        }
    }
}

2 个答案:

答案 0 :(得分:1)

使用TryParse而不是像这样的int.parse

           Console.Write("Enter a Principle Amount: ");
           input = Console.ReadLine();
           double.TryParse(input,out p);
           if(p== 0)
           {
             Console.Write("please input valid number");
           }

答案 1 :(得分:0)

我通常使用double.TryParse为它编写一个单独的方法,因为如果转换成功则返回true并将转换后的值分配给out参数。在以下示例中,如果TryParse成功,我将跳出while (true)循环并返回结果。否则,我告诉用户再试一次:

private static double GetDoubleFromUser(string prompt)
{
    double result;

    while (true)
    {
        if (prompt != null) Console.Write(prompt);
        var input = Console.ReadLine();
        if (double.TryParse(input, out result)) break;
        Console.WriteLine("Sorry, that is not a valid number. Please try again...");
    }

    return result;
}

然后,在您的主要代码中,您不必担心输入和输出或验证,您可以执行以下操作:

double principal = GetDoubleFromUser("Enter a Principal Amount: ");
double years = GetDoubleFromUser("Enter Number of Years: ");
double rate = GetDoubleFromUser("Enter Interest rate: ");