java - Comparable interface project -
i'm stuck on project, far have got:
public class myint implements comparable<myint> { private int value; myint(int x) { value = x; } public string tostring() { return ("" + value); } public int intvalue() { return value; } public int compareto(myint rhs) { myint myint = (myint) rhs; int myinteger = myint.intvalue(); int result = 0; if (value < myinteger) { result = -1; } else if (value == myinteger) { result = 0; } else { result = +1; } return result; } }
and question: consider following java library interface:
public interface comparable<t> { int compareto(t rhs); }
complete implementation of class below implements above interface (note interface automatically imported java – not re-type in project). compareto method should return -1 if value less rhs.value, 0 if both sides equal , +1 if value greater rhs.value.
public class myint implements comparable<myint> { private int value; myint(int x) {...} public string tostring() {...} public int intvalue() {...} public int compareto(myint rhs){...} }
now need implement comparable interface in class performs basic arithmetic rational numbers, best use inheritance achieve this?the class :
public class rational { private int num; private int denom; public rational() { this(0,1); } public rational(int num, int denom) { this.num = num; this.denom = denom; } int getnum() { return num; } int getdenom() { return denom; } public rational add(rational rhs) { return new rational(num * rhs.denom + rhs.num * denom, denom * rhs.denom); } public rational subtract(rational rhs) { return new rational(num * rhs.denom - rhs.num * denom, denom * rhs.denom); } public rational multiply(rational rhs) { return new rational(num * rhs.num, denom * rhs.denom); } public rational divide(rational rhs) { return new rational(num * rhs.denom, denom * rhs.num); } public string tostring() { string result; if (num == 0) result = "0"; else if (denom == 1) result = num + ""; else result = num + "/" + denom; return result; } public static void main(string[] args) { rational r1 = new rational(1, 2); // 1/2 rational r2 = new rational(3, 4);// 3/4 rational result = new rational(); result = r1.add(r2); system.out.println(result); rational result1 = new rational(); result1 = r1.subtract(r2); system.out.println(result1); rational result2 = new rational(); result2 = r1.multiply(r2); system.out.println(result2); rational result3 = new rational(); result3 = r1.divide(r2); system.out.println(result3); }
}
you need compare this.intvalue()
(the current instance) , rhs.intvalue()
(the "right hand side"). comparing rhs
(by aliasing myint
) should return 0. , storing result temporary variable doesn't seem server purpose in code. like
// myint myint = (myint) rhs; if (this.intvalue() < rhs.intvalue()) { return -1; } else if (this.intvalue() == rhs.intvalue()) { return 0; } return 1;
Comments
Post a Comment