Advertisement
korobushk

Untitled

Apr 16th, 2020
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. public class MainProgram {
  2.  
  3. public static void main(String[] args) {
  4. Money a = new Money(10, 0);
  5. Money b = new Money(3, 50);
  6.  
  7. Money c = a.minus(b);
  8.  
  9. System.out.println(a); // 10.00e
  10. System.out.println(b); // 3.50e
  11. System.out.println(c); // 6.50e
  12.  
  13. c = c.minus(a); // NB: a new Money object is created, and is placed "at the end of the strand connected to c"
  14. // the old 6.5 euros at the end of the strand disappears and the Java garbage collector takes care of it
  15.  
  16. System.out.println(a); // 10.00e
  17. System.out.println(b); // 3.50e
  18. System.out.println(c); // 0.00e
  19.  
  20. }
  21. }
  22.  
  23.  
  24.  
  25. public class Money {
  26.  
  27. private final int euros;
  28. private final int cents;
  29.  
  30. public Money(int euros, int cents) {
  31.  
  32. if (cents > 99) {
  33. euros = euros + cents / 100;
  34. cents = cents % 100;
  35. }
  36.  
  37. this.euros = euros;
  38. this.cents = cents;
  39. }
  40.  
  41. public int euros() {
  42. return this.euros;
  43. }
  44.  
  45. public int cents() {
  46. return this.cents;
  47. }
  48.  
  49. public String toString() {
  50. String zero = "";
  51. if (this.cents < 10) {
  52. zero = "0";
  53. }
  54.  
  55. return this.euros + "." + zero + this.cents + "e";
  56. }
  57.  
  58. public boolean lessThan(Money compared) {
  59. if (this.euros < compared.euros) {
  60. return true;
  61. }
  62. if (this.euros == compared.euros && this.cents < compared.cents) {
  63. return true;
  64. }
  65. return false;
  66. }
  67.  
  68. public Money plus(Money addition) {
  69. Money newMoney = new Money(addition.euros + this.euros, addition.cents + this.cents);// create a new Money object that has the correct worth
  70.  
  71. return newMoney;
  72. }
  73.  
  74. public Money minus(Money decreaser) {
  75.  
  76. int e =decreaser.euros-this.euros;
  77. int c= decreaser.cents-this.cents;
  78.  
  79.  
  80. Money newMinus = new Money (e,c);
  81.  
  82. return newMinus;
  83.  
  84. }
  85.  
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement