View Javadoc
1   package calculator.atoms;
2   
3   import calculator.Expression;
4   import calculator.operations.Operation;
5   import calculator.atoms.visitor.AtomVisitor;
6   import calculator.functions.BinaryFunction;
7   import calculator.functions.UnaryFunction;
8   import visitor.Visitor;
9   import java.util.Objects;
10  
11  /**
12   * Rationnal Number type is used to represent fractions e.g. 1/2
13   * 
14   * @see Expression
15   * @see Operation
16   * @see Atom
17   */
18  public class Rationnal implements Atom {
19  
20  	private final org.apache.commons.numbers.fraction.Fraction value;
21  
22  	/**
23  	 * Constructor method
24  	 * * @param numerator The numerator
25  	 * 
26  	 * @param denominator The denominator
27  	 */
28  	public Rationnal(int numerator, int denominator) {
29  		try {
30  			this.value = org.apache.commons.numbers.fraction.Fraction.of(numerator, denominator);
31  		} catch (ArithmeticException e) {
32  			throw new IllegalArgumentException("Denominator cannot be zero", e);
33  		}
34  	}
35  
36  	/**
37  	 * Constructor method for a whole number
38  	 * * @param value The integer value (e.g., 5 becomes 5/1)
39  	 */
40  	public Rationnal(int value) {
41  		this.value = org.apache.commons.numbers.fraction.Fraction.of(value);
42  	}
43  
44  	/**
45  	 * Constructor method from an existing Fraction object
46  	 * * @param value The commons-numbers Fraction object
47  	 */
48  	public Rationnal(org.apache.commons.numbers.fraction.Fraction value) {
49  		this.value = value;
50  	}
51  
52  	/**
53  	 * getter method to obtain the value contained in the object
54  	 *
55  	 * @return The commons-numbers Fraction number contained in the object
56  	 */
57  	public org.apache.commons.numbers.fraction.Fraction getValue() {
58  		return value;
59  	}
60  
61  	@Override
62  	public Atom apply(Operation o, Atom a) {
63  		return o.op(this, (Rationnal) a);
64  	}
65  
66  	@Override
67  	public Atom apply(BinaryFunction f, Atom a) {
68  		return f.op(this, (Rationnal) a);
69  	}
70  
71  	@Override
72  	public Rationnal apply(UnaryFunction o) {
73  		return o.op(this);
74  	}
75  
76  	@Override
77  	public void accept(AtomVisitor v) {
78  		v.visit(this);
79  	}
80  
81  	@Override
82  	public void accept(Visitor v) {
83  		v.visit(this);
84  	}
85  
86  	@Override
87  	public boolean equals(Object o) {
88  		if (o == null)
89  			return false;
90  		if (this == o)
91  			return true;
92  		if (!(o instanceof Rationnal))
93  			return false;
94  		Rationnal other = (Rationnal) o;
95  		return this.value.equals(other.getValue());
96  	}
97  
98  	@Override
99  	public int hashCode() {
100 		return Objects.hash(value);
101 	}
102 
103 	public int getNumerator() {
104 		return value.getNumerator();
105 	}
106 
107 	public int getDenominator() {
108 		return value.getDenominator();
109 	}
110 
111 	@Override
112 	public String toString(){ return value.toString(); };
113 
114 }