Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Point setters


Please consult the for setters of the properties x, y, r, and a below:

using System;

public class Point {

  // Polar representation of points:
  private double radius, angle;            // radius, angle

  public enum PointRepresentation {Polar, Rectangular}

  // Point constructor:
  public Point(PointRepresentation pr, double n1, double n2){
    if (pr == PointRepresentation.Polar){
      radius = n1; angle = n2;
    } 
    else if (pr == PointRepresentation.Rectangular){
      radius = RadiusGivenXy(n1, n2);
      angle  = AngleGivenXy(n1, n2);
    } else {
      throw new Exception("Should not happen");
    }
  }   

  public double x {
    get {
      return XGivenRadiusAngle(radius, angle);}
    set {
      double yBefore = YGivenRadiusAngle(radius, angle);
      angle = AngleGivenXy(value, yBefore);
      radius = RadiusGivenXy(value, yBefore);
    }
  }   

  public double y {
    get {
      return YGivenRadiusAngle(radius, angle);}
    set {
      double xBefore = XGivenRadiusAngle(radius, angle);
      angle = AngleGivenXy(xBefore, value);
      radius = RadiusGivenXy(xBefore, value);
    }
  }   

  public double r {
    get {
     return radius;}
    set {
     radius = value;}
  }   

  public double a {
    get {
     return angle;}
    set {
     angle = value;}
  }   

  public void Move(double dx, double dy){
    x += dx;  y += dy;
  }

  public void Rotate(double angle){
    a += angle;
  }

  public override string ToString(){
    return  "(" + x + "," + y + ")" + " " +  "[r:" + r + ", a:" + a + "]  ";
  }

  protected static double RadiusGivenXy(double x, double y){
    return Math.Sqrt(x * x + y * y);
  }

  protected static double AngleGivenXy(double x, double y){
    return Math.Atan2(y,x);
  }

  protected static double XGivenRadiusAngle(double r, double a){
    return r * Math.Cos(a);
  }

  protected static double YGivenRadiusAngle(double r, double a){
    return r * Math.Sin(a);
  }


}