Reputation:
So I had have a simple application for school. Which does subtracting, dividing, multiplying and adding on fractions.
It worked quite good, but now with 1 fraction I'm getting an error. Fraction: 28/16 - 42/24
Exception in thread "main" java.lang.ArithmeticException: / by zero
at sample.Breuk.reduce(Breuk.java:70)
at sample.Breuk.subtract(Breuk.java:44)
at sample.Main.main(Main.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
So i went to the line where it goes wrong and it turned out it was at subtracting the fraction.
Now I calculated the fraction (28/16 - 42/24) and the result = 0.
So I know where my bug is and what is going wrong, but I don't know how to fix this. Anybody having some tips for me?
public Breuk subtract(Breuk other){
int d = teller * other.teller;
int n1 = noemer * other.teller;
int n2 = other.noemer * teller;
Breuk b = new Breuk(n1-n2,d);
b.reduce();
return b;
}
private void reduce() {
int i = Math.min(Math.abs(noemer), Math.abs(teller));
if (i == 0) {
System.out.println("Error");
}
while ((noemer % i != 0) || (teller % i != 0)) //BUG IS HERE//
i--;
noemer = noemer / i;
teller = teller / i;
}
}
MAIN:
Breuk a = new Breuk(28,16);
Breuk b = new Breuk(42,24);
Breuk g = a.subtract(b); // Breuk A - Breuk b
System.out.println(a + " - " + b + " = "+ g);
Upvotes: 2
Views: 128
Reputation: 82899
The result of the subtraction is Breuk(0, 384)
, i.e. in reduce
, i
starts out as 0
. You print the "error" (which is not really an error in this case), but then continue anyways.
It seems like, in reduce
you are trying to calculate the greatest common divisor by starting with i
as the lower of noemer
and teller
and reducing it until it is a divisor of both. But this will fail if one of the two is 0
, as in the case of Breuk(0, 384)
. To get this case correct, you'd have to start with the higher of the two, as 0 % 384 == 0
, but 384 % 0 == ERROR
, i.e.
int i = Math.max(Math.abs(noemer), Math.abs(teller));
Alternatively, you could just use Euclid's Algorithm to get the greatest common divisor.
private void reduce() {
int gcd = gcd(noemer, teller);
noemer /= gcd;
teller /= gcd;
}
private int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
Both will correctly reduce the fraction 0/384
to 0/1
and, e.g., 6/14
to 3/7
Upvotes: 2