mercredi 29 mars 2017

Name "shape" does not exist in the current context

For optimization, I'm declaring children of a parent class "Shape" in an if-else structure with the name "shape" and, then, because they share a parent and its methods, coding the interaction just using "shape" instead of having it reappear several times within the if-else. I know I could just use a function, but that doesn't utilize inheritance properly and I still won't know why it didn't work.

Classes:

abstract class Shape
{
    public string shapeText { get; set; }
    public string image { get; set; }

    abstract public string GetParameterFormula();
    abstract public double GetParameter(double side);
}

class Triangle : Shape
{
    public Triangle()
    {
       image = "   ^   \n  / \\  \n /   \\ \n --- ";
       shapeText = "Triangle";
    }

    public override string GetParameterFormula()
    {
        return "'(base * height) / 2'";
    }

    public override double GetParameter(double side)
    {
        return (Math.Sqrt(Math.Pow(side, 2) * Math.Pow(side / 2.0, 2)) * side) / 2;
    }
}

class Square : Shape
{
  public Square()
  {
    image = " ___ \n|   |\n|   |\n --- ";
    shapeText = "Square";
  }

  public override string GetParameterFormula()
  {
    return "'base^2'";
  }

  public override double GetParameter(double side)
  {
    return Math.Pow(side, 2);
  }
}

class Circle : Shape
{
  public Circle()
  {
    image = "  ___\n /   \\ \n |   |\n \\   /\n  ---";
    shapeText = "Circle";
  }

  public override string GetParameterFormula()
  {
    return "'pi * r^2'";
  }

  public override double GetParameter(double rad)
  {
    return Math.PI * Math.Pow(rad, 2);
  }
}

Main:

string shapeType = "";
    double side = 0;
    while (true)
    {
      Console.WriteLine("What type of shape? - (cir/tri/sqr");
      shapeType = Console.ReadLine();
      Console.WriteLine("How long are the sides, or the radius?");
      side = Convert.ToDouble(Console.ReadLine());
      if (shapeType == "cir")
      {
        Circle shape = new Circle();
      }
      else if (shapeType == "tri")
      {
        Triangle shape = new Triangle();
      }
      else
      {
        Square shape = new Square();
      }


      Console.WriteLine("The area formula for a " + shape.shapeText + " is " + shape.GetParameterFormula() + ".");
      Console.WriteLine("The area of a " + shape.shapeText + " with sides/radius of length " + side + " is " + shape.GetParameter(side));
    }

Aucun commentaire:

Enregistrer un commentaire