尝试catch阻止问题

时间:2017-07-16 16:55:49

标签: c#

我遇到的问题是每次我用try catch包围(用户被要求输入信息),所以如果他们输入了错误的东西或错误地输入,则会抛出错误。当我把try catch它没有工作时它就结束了程序。如果我现在就像现在一样离开尝试捕获并且用户只是按下输入它会导致程序崩溃..

namespace MaxHeartRate

{

class Program
{

    static void Main(string[] args)
    {
        // Display program instructions
        DisplayInstructions();

        // Collected user info
        CollectUserInfo();

    }
    static void DisplayInstructions()
    {
        Console.WriteLine("************************************************");
        Console.WriteLine("This program will Calculate your Max Heart Rate");
        Console.WriteLine("Also your Mininum and Maximum target Heart rate");
        Console.WriteLine("You will have to enter your info in when promted");
        Console.WriteLine("************************************************");
        return;
    }
    static void CollectUserInfo()
    {
        // Declar Variables
        string firstName, lastName;
        int birthYear = 0;
        int currentYear = 0;
        int age;
        double maxHeartRate, minTargetHeartRate, maxTargetHeartRate;

        try
        {
            // User is asked to enter info
            Console.Write("Enter your first Name: ");
            firstName = Console.ReadLine();
            Console.Write("Enter your last name: ");
            lastName = Console.ReadLine();
            Console.Write("Enter the current year: ");
            currentYear = int.Parse(Console.ReadLine());
            Console.Write("Enter your birth year: ");
            birthYear = int.Parse(Console.ReadLine());


            // Find Age
            age = findAge(currentYear, birthYear);

            // Find Max Heart rate
            maxHeartRate = findMaxHR(age);

            // Find Minimum Target Heart Rate
            minTargetHeartRate = findMinTHR(maxHeartRate);

            // Find Maximum Target Heart Rate
            maxTargetHeartRate = findMaxTHR(maxHeartRate);

            // Display Information
            DisplayInformation(firstName, lastName, age, maxHeartRate, minTargetHeartRate, maxTargetHeartRate);
        }
        catch (Exception)
        {

            Console.WriteLine("Invalid input. Please try again");
        }

        // Methods
    }
    static int findAge(int cYear, int bYear)
    {
        int age = cYear - bYear;
        return age;
    }
    static int findMaxHR(int age)
    {
        int MHR = 220 - age;
        return MHR;
    }
    static double findMinTHR(double maxHeartRate)
    {
        double minTHR = maxHeartRate * 0.50;
        return minTHR;
    }
    static double findMaxTHR(double maxHeartRate)
    {
        double maxTHR = maxHeartRate * 0.85;
        return maxTHR;
    }
    // Display information
    static void DisplayInformation(string firstName, string lastName, int age, double maxHeartRate, double minTargetHeartRate, double maxTargetHeartRate)
    {
        Console.WriteLine();
        Console.WriteLine("************************************************");
        Console.WriteLine("Hello " + firstName + " " + lastName + " You are " + age + " Years old" +
            "\n" + "\nYour Max Heart rate is " + maxHeartRate +
            " BPM" + "\n" + "\nYour Minimum Target Heart rate is " + minTargetHeartRate + " BPM" +
            "\n" + "\nwith a Maximum Target Heart rate of " + maxTargetHeartRate + " BPM");
        Console.WriteLine("************************************************");
        Console.Write("Push enter to exit");
        Console.ReadKey();
    }
}

}

2 个答案:

答案 0 :(得分:0)

以下是如何通过重试尝试从用户获取有效输入的示例:

int currentYear;
while (true)
{
    var currentYearText = Console.ReadLine();
    if (int.TryParse(currentYearText, out currentYear))
    {
        // User entered a valid integer
        // Validating that integer
        if (currentYear > 2000 && currentYear < 2050)
        {
            break;
        }
    }

    Console.Write("Please enter valid year between 2000 and 2050");
}

如果用户输入无效数据,将要求他再试一次。如果用户输入有效,代码将退出循环并转到下一个语句。

答案 1 :(得分:0)

首先,您必须在try / catch中定义currentYear(由于编译器解释代码路径而尝试和捕获)或声明时。否则,您会在CS0165: Use of unassigned local variable 'currentYear'

的行中获得age = findAge(currentYear, birthYear)

以下代码有效:

static void CollectUserInfo()
{
    // Declar Varibals
    string firstName, lastName;

    // We can define these here so that there isn't a compiler error.
    int birthYear = 0;
    int currentYear = 0;
    int age;
    double maxHeartRate, minTargetHeartRate, maxTargetHeartRate;

    // User is asked to enter info
    Console.Write("Enter your first Name: ");
    firstName = Console.ReadLine();
    Console.Write("Enter your last name: ");
    lastName = Console.ReadLine();
    try
    {
        Console.Write("Enter the current year: ");
        currentYear = int.Parse(Console.ReadLine());
        Console.Write("Enter your birth year: ");
        birthYear = int.Parse(Console.ReadLine());
    } 
    catch (Exception)
    {
        // The result of the error. 
        Console.WriteLine("Invalid input.");
        CollectUserInfo();
    }
    // Find Age
    age = findAge(currentYear, birthYear);

    // Find Max Heart rate
    maxHeartRate = findMaxHR(age);

    // Find Minimum Target Heart Rate
    minTargetHeartRate = findMinTHR(maxHeartRate);

    // Find Maximum Target Heart Rate
    maxTargetHeartRate = findMaxTHR(maxHeartRate);

    // Display Information
    DisplayInformation(firstName, lastName, age, maxHeartRate, minTargetHeartRate, maxTargetHeartRate);

// Methods
}