Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm very stuck on a project, so far I 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 this is the question:
Consider the following Java Library interface:
public interface Comparable<T> {
int compareTo(T rhs);
}
Complete the implementation of the class below that implements the above
interface (note this interface is automatically imported by java – do NOT
re-type it in your project). The compareTo method should return -1 if
value is less than rhs.value, 0 if both sides are equal and +1 if value is
greater than 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 I need to implement the comparable interface in another class which performs basic arithmetic with rational numbers, would it be best to use inheritance to 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 to compare this.intValue() (the current instance) and rhs.intValue() (the "right hand side"). Comparing rhs to itself (by aliasing it to myInt) should always return 0. And storing the result as a temporary variable doesn't seem to server any purpose in your code. You could do something like
// MyInt myInt = (MyInt) rhs;
if (this.intValue() < rhs.intValue()) {
return -1;
} else if (this.intValue() == rhs.intValue()) {
return 0;
}
return 1;
No need to do explicit casting of your parameter (MyInt rhs), and since you are simply comparing two integers, use static compare method from Integer:
public int compareTo(MyInt rhs) {
return Integer.compare(this.value, rhs.intValue());
}
I would suggest to change your int field to Integer to avoid performance loss in autoboxing of primitives
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I'm learner of Java.
I'm trying to convert decimal to fraction using BigInteger in Rational class.
If I print the numerator and denominator, right output comes out.
However, when I add, subtract, multiply, and divide, some strange output come out.
For example when I inputs
3.25 -3
The output is
13 4
-3 1
RationalTest#14ae5a5
RationalTest#7f31245a
RationalTest#6d6f6e28
RationalTest#135fbaa4
What is wrong with my code? What is that hashcode?
I couldn't find out in the internet, so I need your help:<
import java.util.Scanner;
import java.math.*;
public class TestTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
RationalTest r1 = RationalTest.getFraction(sc.next());
RationalTest r2 = RationalTest.getFraction(sc.next());
//Test if the right numerator and denominator comes out
System.out.println(r1.getNumerator()+" "+r1.getDenominator());
System.out.println(r2.getNumerator()+" "+r2.getDenominator());
System.out.println(r1.add(r2));
System.out.println(r1.subtract(r2));
System.out.println(r1.multiply(r2));
System.out.println(r1.divide(r2));
}
}
class RationalTest extends Number implements Comparable<RationalTest>
{
private static final long serialVersionUID = 1L;
private BigInteger numerator = BigInteger.ZERO;
private BigInteger denominator = BigInteger.ONE;
public RationalTest()
{
this(BigInteger.ZERO, BigInteger.ONE);
}
//Find GCD of numerator and denominator
public RationalTest(BigInteger numerator, BigInteger denominator)
{
BigInteger gcd = gcd(numerator, denominator);
this.numerator = ((denominator.compareTo(BigInteger.ZERO)>0) ? new BigInteger("1"):new BigInteger("-1")).multiply(numerator.divide(gcd));
this.denominator = denominator.abs().divide(gcd);
}
//Converting decimal to fraction
public static RationalTest getFraction(String s)
{
int result=-1;
for(int i=0; i<s.length(); i++)
{
if(s.charAt(i)=='.')
{
result=1;
break;
}
else
result=0;
}
//If result=1, String s is a decimal
if(result==1)
{
double d = Double.parseDouble(s);
long num = (long) Math.floor(d); // Only the int part
double denom = d-num; // Only the decimal part
int digitDec = s.length()-1-s.indexOf('.');
long up = (int) (denom*Math.pow(10, digitDec)); // numerator of denom
long down = (int) Math.pow(10, digitDec); // denominator of denim
return new RationalTest(BigInteger.valueOf(down*num+up), BigInteger.valueOf(down));
}
//If result=0, String s is not a decimal
else
{
return new RationalTest(BigInteger.valueOf(Long.parseLong(s)), BigInteger.ONE);
}
}
private static BigInteger gcd(BigInteger n, BigInteger d)
{
BigInteger n1 = n.abs();
BigInteger n2 = d.abs();
BigInteger gcd = BigInteger.ONE;
for(BigInteger k=BigInteger.ONE; k.compareTo(n1)<=0 && k.compareTo(n2)<=0; k=k.add(BigInteger.ONE))
{
if(n1.mod(k).equals(BigInteger.ZERO) && n2.mod(k).equals(BigInteger.ZERO))
gcd = k;
}
return gcd;
}
public BigInteger getNumerator()
{
return numerator;
}
public BigInteger getDenominator()
{
return denominator;
}
public RationalTest add(RationalTest secondRationalTest)
{
BigInteger n = (numerator.multiply(secondRationalTest.getDenominator())).add(denominator.multiply(secondRationalTest.getNumerator()));
BigInteger d = denominator.multiply(secondRationalTest.getDenominator());
return new RationalTest(n, d);
}
public RationalTest subtract(RationalTest secondRationalTest)
{
BigInteger n = (numerator.multiply(secondRationalTest.getDenominator())).subtract(denominator.multiply(secondRationalTest.getNumerator()));
BigInteger d = denominator.multiply(secondRationalTest.getDenominator());
return new RationalTest(n, d);
}
public RationalTest multiply(RationalTest secondRationalTest)
{
BigInteger n = numerator.multiply(secondRationalTest.getNumerator());
BigInteger d = denominator.multiply(secondRationalTest.getDenominator());
return new RationalTest(n, d);
}
public RationalTest divide(RationalTest secondRationalTest)
{
BigInteger n = numerator.multiply(secondRationalTest.getDenominator());
BigInteger d = denominator.multiply(secondRationalTest.getNumerator());
return new RationalTest(n, d);
}
#Override
public boolean equals(Object other)
{
if((this.subtract((RationalTest)(other))).getNumerator().equals(BigInteger.ZERO))
return true;
else
return false;
}
#Override
public int intValue()
{
return (int)doubleValue();
}
#Override
public float floatValue()
{
return (float)doubleValue();
}
#Override
public double doubleValue()
{
double x = this.getNumerator().doubleValue();
double y = this.getDenominator().doubleValue();
return x/y;
}
#Override
public long longValue()
{
return (long)doubleValue();
}
#Override
public int compareTo(RationalTest o) {
if(this.subtract(o).getNumerator().compareTo(BigInteger.ZERO)>0)
return 1;
else if(this.subtract(o).getNumerator().compareTo(BigInteger.ZERO)<0)
return -1;
else
return 0;
}
}
Oh I found out that I have to return string using toString()..
Thanks for your help!
I am working on this program and keep getting this result.
To convert fractional measures,
enter the fractional measure you want to convert: 3/4
Enter the fractional amount to reduce/increase it by: 1/2
The converted measurement is: Fraction#6750cf54
The part is bold is the problem.
This is my main program.
import java.util.*; // Scanner
import java.io.*; // PrintStream
public class Pierre1 extends Object
{
public static void main(String args[])
{
PrintStream theScreen = new PrintStream(System.out);
Scanner theKeyboard = new Scanner(System.in);
theScreen.println("\nTo convert fractional measures,");
theScreen.print(" enter the fractional measure you want to convert: ");
Fraction oldMeasure = new Fraction();
oldMeasure.read(theKeyboard);
theScreen.print("\nEnter the fractional amount to reduce/increase it by: ");
Fraction scaleFactor = new Fraction(1,6);
scaleFactor.read(theKeyboard);
Fraction newMeasure = oldMeasure.times(scaleFactor);
theScreen.print("\nThe converted measurement is: ");
theScreen.print(newMeasure);
theScreen.println();
theScreen.println();
}
}
This is my other program.
import java.util.*; // Scanner
import java.io.*; // PrintStream
public class Fraction extends Object
{
private int myNumerator = 0;
private int myDenominator = 0;
public void print(PrintStream out)
{
System.out.print(myNumerator + "/" + myDenominator);
}
public Fraction()
{
myNumerator = 0;
myDenominator = 1;
}
public Fraction(int numerator, int denominator)
{
myNumerator = numerator;
myDenominator = denominator;
}
private int numerator()
{
return myNumerator;
}
private int denominator()
{
return myDenominator;
}
public void read (Scanner in)
{
String fraction = in.next();
StringTokenizer parser = new StringTokenizer(fraction, "/", false);
if (parser.countTokens() != 2)
throw new RuntimeException("Bad Fraction Format");
myNumerator = Integer.parseInt(parser.nextToken());
myDenominator = Integer.parseInt(parser.nextToken());
}
Fraction times(Fraction rightOperand)
{
Fraction result
= new Fraction(myNumerator*rightOperand.numerator(),
myDenominator*rightOperand.denominator());
result.simplify(result);
return result;
}
public Fraction simplify(Fraction getGcd)
{
Fraction result = new Fraction();
int num = numerator();
int den = denominator();
int gcd = greatestCommonDivisor(num, den);
if (gcd == 0)
return result;
else
{
myNumerator = myNumerator / gcd;
myDenominator = myDenominator / gcd;
}
return result;
}
private static int greatestCommonDivisor(int alpha, int beta)
{
alpha = Math.abs(alpha); // take absolute values of operands
beta = Math.abs(beta);
if (beta == 0) // base case
return alpha;
else // induction step
{
int remainder = alpha % beta;
return greatestCommonDivisor(beta, remainder);
}
}
}
What do I need to do to fix this?
I have been scanning the programs to find the problem, but my limited java experience is getting the best of me. Any help is greatly appreciated. Thanks in advance!
have a look at the Fraction class that I use (it fixes some of your flaws: numerator and denumerator should be final, etc.)
// code by jph
package sys.mat;
/** non degenerate integer fraction in normal form */
public class Fraction implements Comparable<Fraction> {
/** numerator */
public final int num;
/** denominator (always greater than zero) */
public final int den;
public static int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
/** #param num
* #param den has to be non-zero
* #throws {#link ArithmeticException} if den is zero */
public Fraction(final int num, final int den) {
int gcd = gcd(num, den);
int res = den / gcd;
if (0 < res) {
this.num = num / gcd;
this.den = res;
} else {
this.num = -num / gcd;
this.den = -res;
}
}
public Fraction add(Fraction myFraction) {
return new Fraction(num * myFraction.den + den * myFraction.num, den * myFraction.den);
}
public Fraction sub(Fraction myFraction) {
return new Fraction(num * myFraction.den - den * myFraction.num, den * myFraction.den);
}
public Fraction mul(Fraction myFraction) {
return new Fraction(num * myFraction.num, den * myFraction.den);
}
public Fraction mul(int myInt) {
return new Fraction(num * myInt, den);
}
public Fraction div(Fraction myFraction) {
return new Fraction(num * myFraction.den, den * myFraction.num);
}
/** also denoted reciprocal
*
* #return den/num */
public Fraction inverse() {
return new Fraction(den, num);
}
/** #return true if den == 1 */
public boolean isInteger() {
return den == 1;
}
public double toDouble() {
return num / (double) den;
}
/** may only be called if isInteger() returns true
*
* #return num */
public int toInteger() {
if (!isInteger()) // assert den == 1
throw new RuntimeException(toString() + " is no integer");
return num;
}
#Override
public int compareTo(Fraction myFraction) {
// return num * myFraction.den - den * myFraction.num; // does not work for big integers
return Double.compare(toDouble(), myFraction.toDouble());
}
public boolean equalsInteger(int value) {
return equals(new Fraction(value, 1));
}
#Override
public boolean equals(Object myObject) {
if (myObject == null) // || !(myObject instanceof Fraction)
return false;
Fraction myFraction = (Fraction) myObject;
return num == myFraction.num && den == myFraction.den; // sufficient since in normal form
}
#Override
public int hashCode() {
// n / 1 is mapped to n, thus is identical to getInteger()
return num + den - 1;
}
#Override
public String toString() {
return num + "/" + den;
}
}
public class Fraction
{
public Franction(int n, int d)
{
int num = n;
int denom = d;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
Hello, I'm trying to learn Java... The book I'm working out of suggests that the output of the code above should print "Fraction = 5/10", but when I try it I just receive "Fraction = Fraction#33469a69" which I assume is printing the reference to where it is stored? I understand how it is suppose to work with the constructor I just don't receive the expected output. Any help would be greatly appreciated... Thanks!
To get the desired output, you need to overload toString() method in the Franction class. This method is used to determine textual representation of the object. By default, it is ClassName#hashCode.
Also, you probably would like to store the values you receive in the constructor as fields. Right now, you store the numerator and denominator in constructor's local variables, that are destroyed as soon as the constructor exits.
Try something like this:
public class Fraction
{
private final int num
private final int denom;
public Franction(int n, int d)
{
this.num = n;
this.denom = d;
}
#Override
String toString()
{
return String.format("%d/%d", num, denom);
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1);
}
}
You need to override the toString method for the same
public String toString(){
StringBuilder stringToReturn = new StringBuilder();
stringToReturn.append(this.num);
stringToReturn.append("/");
stringToReturn.append(this.denom);
return stringToReturn.toString();
}
You have to override the toString() function in your Fraction class.
As per docs of toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
So
Fraction#33469a69 is the textual representation of Fraction class.
To get the required output, write the logic in overridden toString method in Object class and return the string there.
A simple toString implementation looks like
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.someMemeber); //will be in String format
result.append(this.someMemeber);
return result.toString();
}
Try this
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1.getNum() + "/" + f1.getDenom());
}
}
Alternative (Better way to do this)
public class Fraction
{
private int num;
private int denom;
public Franction(int n, int d)
{
num = n;
denom = d;
}
public int getNum()
{
return num;
}
public int getDenom()
{
return denom;
}
#Override
public String toString(){
return (f1.getNum() + "/" + f1.getDenom());
}
public static void main(String[] args)
{
Fraction f1 = new Fraction(5,10);
System.out.println("Fraction = " + f1 );
}
}
You need to study more about encapsulation , the Object class and the toString() method.
Happy Coding :)
Try the following:
public class Fraction {
private final int num;
private final int denom;
public Fraction(int num, int denom) {
this.num = num;
this.denom = denom;
}
#Override
public String toString() {
return num + "/" + denom;
}
public static void main(String[] args) {
Fraction f1 = new Fraction(5, 10);
System.out.println("Fraction = " + f1);
}
}
You have to store the values in the object you create. Then override the toString method of Object to get your desired output.
Output:
Fraction = 5/10
All you are doing is printing out the Object.
If you want to print the contents of the Object you will to create a toString method in you class.
see http://www.javapractices.com/topic/TopicAction.do?Id=55
Can anyone help me compare an Integer to a Double using generics?
This is what I have:
public static <T extends Comparable<? super T>> int compare(T arg1, T arg2)
{
return arg1.compareTo(arg2);
}
public static void main(String[] args)
{
Number i = new Integer(5);
Number j = new Double(7);
System.out.println(GenericsTest.compare(i, j));
}
The error message I get is:
Bound mismatch: The generic method compare(T, T) of type GenericsTest is not applicable for the arguments (Number, Number). The inferred type Number is not a valid substitute for the bounded parameter >
The idea of this solution is to widen to BigDecimal and then compare the two numbers (now is cleaner but somehow formatting doesn't work). Note you may reuse this static comparator without having to cast to double anywhere else. In the implementation you do need conversion to double not to lose information, basically you widen to the most general representation.
private static final Comparator<Number> NUMBER_COMPARATOR = new Comparator<Number>() {
private BigDecimal createBigDecimal(Number value) {
BigDecimal result = null;
if (value instanceof Short) {
result = BigDecimal.valueOf(value.shortValue());
} else
if (value instanceof Long) {
result = BigDecimal.valueOf(value.longValue());
} else
if (value instanceof Float) {
result = BigDecimal.valueOf(value.floatValue());
} else
if (value instanceof Double) {
result = BigDecimal.valueOf(value.doubleValue());
} else
if (value instanceof Integer) {
result = BigDecimal.valueOf(value.intValue());
} else {
throw new IllegalArgumentException("unsupported Number subtype: " + value.getClass().getName());
}
assert(result != null);
return result;
}
public int compare(Number o1, Number o2) {
return createBigDecimal(o1).compareTo(createBigDecimal(o2));
};
};
public static void main(String[] args) {
Number i = Integer.valueOf(5);
Number j = Double.valueOf(7);
// -1
System.out.println(NUMBER_COMPARATOR.compare(i, j));
i = Long.MAX_VALUE;
j = Long.valueOf(7);
// +1
System.out.println(NUMBER_COMPARATOR.compare(i, j));
i = Long.MAX_VALUE;
j = Long.valueOf(-7);
// +1
System.out.println(NUMBER_COMPARATOR.compare(i, j));
i = Long.MAX_VALUE;
j = Double.MAX_VALUE;
// -1
System.out.println(NUMBER_COMPARATOR.compare(i, j));
i = Long.MAX_VALUE;
j = Long.valueOf(Long.MAX_VALUE - 1);
// +1
System.out.println(NUMBER_COMPARATOR.compare(i, j));
// sorting Long values
Long[] values = new Long[] {Long.valueOf(10), Long.valueOf(-1), Long.valueOf(4)};
Arrays.sort(values, NUMBER_COMPARATOR);
// [-1, 4, 10]
System.out.println(Arrays.toString(values));
}
As aready said in the comments, Number does not implement Comparable.
But Double and Integer do.
One way to make this work is like this:
public static <T extends Comparable<? super T>> int compare(T arg1, T arg2)
{
return arg1.compareTo(arg2);
}
public static void main(String[] args)
{
Double i = new Integer(5).doubleValue();
Double j = new Double(7);
System.out.println(GenericsTest.compare(i, j));
}
Number doesn't implement Comparable.
Declare both variables as Integer.
private boolean compareObject(Object expected, Object actual) {
if (expected instanceof Number && actual instanceof Number) {
double e = ((Number) expected).doubleValue();
double a = ((Number) actual).doubleValue();
return e == a;
} else {
return com.google.common.base.Objects.equal(expected, actual);
}
}
Create a class that implements Comparable which takes a Number in the constructor.
e.g.
public class GenericNumber implements Comparable<GenericNumber> {
private Number num;
public GenericNumber(Number num) {
this.num = num;
}
// write compare function that compares num member of two
// GenericNumber instances
}
Then simply do this:
GenericNumber i = new GenericNumber(new Integer(5));
GenericNumber j = new GenericNumber(new Double(7));
System.out.println(GenericsTest.compare(i,j));
hi im having trouble getting this to work im getting an error here with my object comparison...how could I cast the inches to a string ( i never used compare to with anything other than strings) , or use comparison operators to compare the intigers,
Object comparison = this.inches.compareTo(obj.inches);
here is my code so far
import java.io.*;
import java.util.*;
import java.lang.Integer;
import java.lang.reflect.Array;
public class Distance implements Comparable<Distance> {
private static final String HashCodeUtil = null;
private int feet;
private int inches;
private final int DEFAULT_FT = 1;
private final int DEFAULT_IN = 1;
public Distance(){
feet = DEFAULT_FT;
inches = DEFAULT_IN;
}
public Distance(int ft, int in){
feet = ft;
inches = in;
}
public void setFeet(int ft){
try {
if(ft<0){
throw new CustomException("Distance is not negative");
}
}
catch(CustomException c){
System.err.println(c);
feet =ft;
}
}
public int getFeet(){
return feet;
}
public void setInches(int in){
try
{
if (in<0)
throw new CustomException("Distance is not negative");
//inches = in;
}
catch(CustomException c)
{
System.err.println(c);
inches = in;
}
}
public int getInches(){
return inches;
}
public String toString (){
return "<" + feet + ":" + inches + ">";
}
public Distance add(Distance m){
Distance n = new Distance();
n.inches = this.inches + m.inches;
n.feet = this.feet + m.feet;
while(n.inches>12){
n.inches = n.inches - 12;
n.feet++;
}
return n;
}
public Distance subtract(Distance f){
Distance m = new Distance();
m.inches = this.inches - f.inches;
m.feet = this.feet - f.feet;
while(m.inches<0){
m.inches = m.inches - 12;
feet--;
}
return m;
}
#Override
public int compareTo(Distance obj) {
// TODO Auto-generated method stub
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == obj) return EQUAL;
if(this.DEFAULT_IN < obj.DEFAULT_FT) return BEFORE;
if(this.DEFAULT_IN > obj.DEFAULT_FT) return AFTER;
Object comparison = this.inches.compareTo(obj.inches);
if (this.inches == obj.inches) return compareTo(null);
assert this.equals(obj) : "compareTo inconsistent with equals";
return EQUAL;
}
#Override public boolean equals( Object obj){
if (obj != null) return false;
if (!(obj intanceof Distance)) return false;
Distance that = (Distance)obj;
( this.feet == that.feet &&
this.inches == that.inches);
return true;
else
return false;
}
#Override public int hashCode(int, int) {
int result = HashCodeUtil.inches;
result = HashCodeUtil.hash(result, inches );
result = HashCodeUtil.hash(result, feet);
ruturn result;
}
You're comparing object references. Try to compare object value; either override hashCode() or compare field values.
#Override
public int compareTo(Distance obj) {
....
if (this == obj) return EQUAL; <--- This
...
}
With this line:
Object comparison = this.inches.compareTo(obj.inches);
you are trying to dereference an int, a primitive type. The compiler should be giving you an error: you can only dereference Objects using the dot .
I'm not sure what you want this compareTo code to do, but it is at this point, to compare primitive types, that you should be using ==:
if (this.inches == obj.inches) return compareTo(null);
Be aware that in this line: if (this == obj) return EQUAL; you are comparing object references, which might or might not be what you want. Since your class doesn't override the equals method, this comparison is equivalent to this.equals(obj).