Reputation: 157
I've checked many stackOverflow questions about operations with objects but I haven't find the solution.
My task is to multiply and divide two objects with these constructors:
public class Fraction {
private int denom;
private int counter;
public Fraction() {
this.counter = 0;
this.denom = 1;
}
public Fraction(int counter) {
this.counter = counter;
this.denom = 1;
}
public Fraction(int counter, int denom) {
this.counter = counter;
if (denom == 0) {
this.denom = 1;
} else
this.denom = denom;
}
}
What would be inside the "multiply" and "divide" methods?
public Fraction multiply(Fraction other) {
}
public Fraction divide(Fraction other) {
}
if this is what I need to use:
Fraction frac1 = new Fraction (2);
Fraction frac2 = new TortSzam(3,4);
fracResult = frac1.divide(frac2);
and the result is: 2.6666666666666665
What I tried by other StackOverflow Questions:
public Fraction multiply(Fraction other) {
final Fraction multi = this;
BigInteger result = new BigInteger;
result.multiply(other);
}
But didn't work.
Thanks in advance.
Upvotes: 0
Views: 60
Reputation: 520978
Multiplying two fractions just means multiplying the numerators, and then dividing that product by the multiplication of the denominators. So you may try:
public Fraction multiply(Fraction other) {
int counter = other.getCounter() * this.counter;
int denim = other.getDenominator() * this.denom;
return new Fraction(counter, denom);
}
I will leave the implementation of division up to you. As a hint, the code would be very similar to the above except that you would use the inverse of one (but not both) of the two fraction inputs.
Upvotes: 2