diff --git a/src/Lfraction.java b/src/Lfraction.java index 2b3579a..e2146ae 100644 --- a/src/Lfraction.java +++ b/src/Lfraction.java @@ -10,28 +10,33 @@ public class Lfraction implements Comparable { // TODO!!! Your debugging tests here } - // TODO!!! instance variables here + private long nu; + private long de; /** Constructor. * @param a numerator * @param b denominator > 0 */ public Lfraction (long a, long b) { - // TODO!!! + if (b < 1) { + throw new RuntimeException("Denominator can't be 0 or less"); + } + this.nu = a; + this.de = b; } /** Public method to access the numerator field. * @return numerator */ public long getNumerator() { - return 0L; // TODO!!! + return this.nu; } /** Public method to access the denominator field. * @return denominator */ public long getDenominator() { - return 1L; // TODO!!! + return this.de; } /** Conversion to string. @@ -39,7 +44,7 @@ public class Lfraction implements Comparable { */ @Override public String toString() { - return null; // TODO!!! + return ""+Long.toString(this.nu)+"/"+Long.toString(this.de); } /** Equality test. @@ -48,7 +53,21 @@ public class Lfraction implements Comparable { */ @Override public boolean equals (Object m) { - return false; // TODO!!! + Lfraction other = (Lfraction) m; + if (other.de == this.de) { + return this.nu == other.nu; + } else { + double dif; + if (other.de > this.de) { + dif = other.de / this.de; + } else { + dif = this.de / other.de; + } + + System.out.println("dif = " + dif); + return (this.nu*dif) == other.nu; + } + } /** Hashcode has to be equal for equal fractions. @@ -79,7 +98,12 @@ public class Lfraction implements Comparable { * @return inverse of this fraction: 1/this */ public Lfraction inverse() { - return null; // TODO!!! + if (this.nu < 1) { + return new Lfraction(-this.de, -this.nu); + } else { + return new Lfraction(this.de, this.nu); + } + } /** Opposite of the fraction. n/d becomes -n/d. @@ -119,14 +143,14 @@ public class Lfraction implements Comparable { */ @Override public Object clone() throws CloneNotSupportedException { - return null; // TODO!!! + return new Lfraction(this.nu, this.de); } /** Integer part of the (improper) fraction. * @return integer part of this fraction */ public long integerPart() { - return 0L; // TODO!!! + return this.nu/this.de; } /** Extract fraction part of the (improper) fraction @@ -141,7 +165,7 @@ public class Lfraction implements Comparable { * @return numeric value of this fraction */ public double toDouble() { - return 0.; // TODO!!! + return new Double(this.nu)/this.de; } /** Double value f presented as a fraction with denominator d > 0. @@ -159,7 +183,7 @@ public class Lfraction implements Comparable { * @return fraction represented by s */ public static Lfraction valueOf (String s) { - return null; // TODO!!! + String[] parts = s.split("/"); + return new Lfraction(Long.parseLong(parts[0]), Long.parseLong(parts[1])); } -} - +} \ No newline at end of file