Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Fraction implements Comparable<Fraction> {
- private int num;
- private int den;
- Fraction(int numerator, int denominator) {
- if (denominator == 0) {
- throw new ArithmeticException("Bannað að deila með núlli");
- }
- this.num = numerator;
- this.den = denominator;
- }
- public Fraction plus(Fraction f) {
- return new Fraction(this.num * f.den + f.num * this.den, this.den * f.den);
- }
- public boolean equals(Fraction f) {
- if (f == null) {
- return false;
- }
- Double a = (double) this.num/this.den;
- Double b = (double) f.num/f.den;
- //tékkum hvort að |a-b| sé nánast 0:
- if (Math.abs(a-b) <= 0.000001) return true;
- else return false;
- }
- @Override
- public int compareTo(Fraction f) {
- Double a = (double) this.num/this.den;
- Double b = (double) f.num/f.den;
- //skilum 0 ef jafntog, -1 ef a<b eða 1 ef a>b:
- if (Math.abs(a-b) <= 0.000001) return 0;
- else if (a<b) return -1;
- else return 1;
- }
- public static void main(String args[]) {
- Fraction p = new Fraction(1, 2);
- Fraction r = new Fraction(-1, -2);
- Fraction q = new Fraction(2, 6);
- Fraction s = new Fraction(1, 4);
- Fraction t = new Fraction(2, 4);
- // Prófum hvort .equals aðferðin sé sjálfhverf (þarf að vera satt)
- System.out.println("p.equals(p): " + p.equals(p));
- // Prófum hvort .equals aðferðin sé samhverf (þarf að vera eins)
- System.out.println("p.equals(r): " + p.equals(r));
- System.out.println("r.equals(p): " + r.equals(p));
- // Prófum hvort .equals aðferðin sé gegnvirk (allt þarf að vera eins)
- System.out.println("p.equals(r): " + p.equals(r));
- System.out.println("r.equals(t): " + r.equals(t));
- System.out.println("p.equals(t): " + p.equals(t));
- // Prófum hvort .equals aðferðin hafni samanburði við null (þarf að vera false):
- System.out.println("t.equals(null): " + t.equals(null));
- // Prófum hvort .compareTo sé sjálfhverf (þarf að vera 0)
- System.out.println("q.compareTo(q): " + q.compareTo(q));
- // Prófum hvort .compareTo sé andsamhverf (þarf að vera mismunandi)
- System.out.println("r.compareTo(q): " + r.compareTo(q));
- System.out.println("q.compareTo(r): " + q.compareTo(r));
- // Prófum hvort .compareTo sé gegnvirk (allt þarf að vera eins)
- System.out.println("r.compareTo(q): " + r.compareTo(q));
- System.out.println("q.compareTo(s): " + q.compareTo(s));
- System.out.println("r.compareTo(s): " + r.compareTo(s));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment