Lektion 10: lösningsförslag

  1. // 1
  2. class Person
  3. {
  4. private int age;
  5. public int Age
  6. {
  7. get
  8. {
  9. return age;
  10. }
  11. set
  12. {
  13. if (value >= 0)
  14. {
  15. age = value;
  16. }
  17. else
  18. {
  19. throw new ArgumentException("Invalid age");
  20. }
  21. }
  22. }
  23. }
  24. // 2
  25. class Account
  26. {
  27. private double balance;
  28. public void Deposit(double amount)
  29. {
  30. balance += amount;
  31. }
  32. public void Withdraw(double amount)
  33. {
  34. if (amount <= balance)
  35. {
  36. balance -= amount;
  37. }
  38. else
  39. {
  40. throw new ArgumentException("Balance too low");
  41. }
  42. }
  43. }
  44. // 2.1
  45. class Account2
  46. {
  47. private double balance;
  48. public void Deposit(double amount)
  49. {
  50. balance += amount;
  51. }
  52. public void Withdraw(double amount)
  53. {
  54. if (amount > balance)
  55. {
  56. balance -= 100;
  57. }
  58. balance -= amount;
  59. }
  60. }
  61. // 3
  62. class SquareLike
  63. {
  64. private double width;
  65. private double height;
  66. public SquareLike(double width, double height)
  67. {
  68. // This calculation can probably be made in a more elegant way (and maybe even a more correct way?), but the details are not relevant for this exercise.
  69. if (width / height <= 1.2 && height / width <= 1.2)
  70. {
  71. // "this" needed to distinguish between argument and field.
  72. this.width = width;
  73. this.height = height;
  74. }
  75. else
  76. {
  77. throw new ArgumentException("Width and height too different");
  78. }
  79. }
  80. }
  81. // 3.1
  82. class SquareLike2
  83. {
  84. private double width;
  85. private double height;
  86. public SquareLike2(double width, double height)
  87. {
  88. ChangeSize(width, height);
  89. }
  90. public void ChangeSize(double width, double height)
  91. {
  92. if (width / height <= 1.2 && height / width <= 1.2)
  93. {
  94. this.width = width;
  95. this.height = height;
  96. }
  97. else
  98. {
  99. throw new ArgumentException("Width and height too different");
  100. }
  101. }
  102. }
  103. // 4
  104. class Temperature
  105. {
  106. // We choose Celsius as our "canonical" representation.
  107. public double Celsius { get; set; }
  108. public double Fahrenheit
  109. {
  110. // We use the 5/9 fraction below for greater accuracy; 0.56 is also fine for our purposes.
  111. get
  112. {
  113. // Convert from Celsius to Fahrenheit.
  114. return (Celsius / (5.0 / 9)) + 32;
  115. }
  116. set
  117. {
  118. // Convert from Fahrenheit to Celsius.
  119. Celsius = (value - 32) * (5.0 / 9);
  120. }
  121. }
  122. }