如何重写此代码以接受用户输入?

时间:2014-10-14 08:51:39

标签: c#

我有以下代码打印right triangle的区域。如您所见,三角形的尺寸被硬编码到程序中。我希望用户输入值xy。我将如何更改以下程序,以便提示用户输入这些值?

public class Triangle
{        
    private int height, length;        
    public Triangle(int x, int y)
    {
        length = x;
        height = y;
    }       
    public double TriArea()
    {
        double area;
        area = 0.5 *(height * length);
        return area;
    }
}
class TriangleArea
{
    public static void Main()
    {            
        Triangle Tri1 = new Triangle(15, 10);            
        Console.WriteLine("Area 1=" + Tri1.TriArea());           
        Triangle myTriangle = new Triangle(12, 5);            
        Console.WriteLine("My Triangle Area =" + myTriangle.TriArea());
        Console.ReadLine();
    }
}
}

1 个答案:

答案 0 :(得分:1)

一种天真的做法是做到以下几点。

Console.WriteLine("Add integer X: ");
int x = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Add integer Y: ");
int y = Convert.ToInt32(Console.ReadLine());

Triangle Tri1 = new Triangle(x, y);            
Console.WriteLine("Area 1=" + Tri1.TriArea()); 

更强大的方法是验证用户输入并具有输入循环,以便用户可以计算多个三角形的面积。它可能如下所示:

static void Main(string[] args)
{
    bool keepPrompting = true;

    while (keepPrompting)
    {
        bool weHaveValidXValue = false;
        int x = 0, y = 0;

        while (!weHaveValidXValue)
        {
            Console.WriteLine("Enter value for X and press return:");

            string xValue = Console.ReadLine();

            weHaveValidXValue = int.TryParse(xValue, out x);

            if (!weHaveValidXValue || x <= 0)
            {
                weHaveValidXValue = false;
                Console.WriteLine("Invalid value");
            }
        }

        bool weHaveValidYValue = false;

        while (!weHaveValidYValue)
        {
            Console.WriteLine("Enter value for Y and press return:");

            string yValue = Console.ReadLine();

            weHaveValidYValue = int.TryParse(yValue, out y);

            if(!weHaveValidYValue || y <= 0)
            {
                weHaveValidYValue = false;
                Console.WriteLine("Invalid value");
            }
        }

        Triangle myTriangle = new Triangle(x, y);

        Console.WriteLine("My Triangle Area = {0}", myTriangle.TriArea());

        Console.WriteLine("Continue? (y/n)");

        string response = Console.ReadLine();

        if(response.Equals("n", StringComparison.InvariantCultureIgnoreCase))
        {
            keepPrompting = false;
        }
    }
}