0

Hello,

First off, thank you to anyone who helps me in advance. I am about as new as one can be to Java, and am having some troubles. In the below code, the goal is to create a fraction. The rules are the denominator has to remain positive and I have to reduce the fraction with its greatest common denominator. The "private static inc common" part was supplied and has to be used. The problem I am having is that when I test it, the denominator is not being made positive by multiplying by -1, and the fraction is not being reduced (i.e. when I add 1/-2 and 1/4 I am getting 2/-8 instead of -1/4. Also, the runtime error will not compile (which is why it is commented out), and I don't know why.

```
public class Fraction
{
private int top, bottom;
public Fraction(int numerator, int denominator) {
top = numerator;
bottom = denominator;
//if (bottom == 0);
//throw new RuntimeError("Attempt to create zero denominator fraction");
}
public int getTop() {
return top;
}
public int getBottom() {
return bottom;
}
private void reduce() {
if (bottom < 0)
{
top *= -1;
bottom *= -1;
}
int factor = common(top,bottom);
top = top/factor;
bottom = bottom/factor;
}
private static int common(int x, int y) {
if ( y == 0 ) return x;
else return common(y, x%y);
}
public Fraction plus(Fraction f) {
int num1 = top;
int num2 = f.top;
int denom1 = bottom;
int denom2 = f.bottom;
int newNum = (num1 * denom2) + (num2 * denom1);
int newDenom = (denom1 * denom2);
return new Fraction(newNum, newDenom);
}
public Fraction minus(Fraction f) {
int num1 = top();
int num2 = f.top();
int denom1 = bottom();
int denom2 = f.bottom();
int newNum = (num1 * denom2) - (num2 * denom1);
int newDenom = (denom1 * denom2);
return new Fraction(newNum, newDenom);
}
public Fraction multiply(Fraction f) {
int num1 = top();
int num2 = f.top();
int denom1 = bottom();
int denom2 = f.bottom();
int newNum = (num1 * num2);
int newDenom = (denom1 * denom2);
return new Fraction(newNum, newDenom);
}
public Fraction divide(Fraction f) {
int num1 = top();
int num2 = f.top();
int denom1 = bottom();
int denom2 = f.bottom();
int newNum = (num1 * denom2);
int newDenom = (num2 * denom1);
return new Fraction(newNum, newDenom);
}
public String toString() {
return top + "/" + bottom;
}
}
```

*Edited 6 Years Ago by Jobie111*: n/a