package sy06.sy01;
import java.util.Scanner;
public class TestFraction {
public static void main(String[] args) {
Fraction f2 = null;
Scanner sc = new Scanner(System.in);
System.out.println("Please enter fraction f1:");
int n1 = sc.nextInt();
int d1 = sc.nextInt();
Fraction f1 = new Fraction(n1, d1);
System.out.println("Please enter fraction f2:");
int n2 = sc.nextInt();
int d2 = sc.nextInt();
f2 = new Fraction(n2, d2);
sc.close();
Fraction addRet = null, subRet = null, mulRet = null, divRet = null;
addRet = f1.add(f2);
subRet = f1.sub(f2);
mulRet = f1.mul(f2);
divRet = f1.div(f2);
System.out.println(f1 + " + " + f2 + " = " + addRet);
System.out.println(f1 + " - " + f2 + " = " + subRet);
System.out.println(f1 + " * " + f2 + " = " + mulRet);
System.out.println(f1 + " / " + f2 + " = " + divRet);
System.out.println(f1 + " equals " + f2 + " ? " + f1.equals(f2));
}
}
class Fraction {
int nume; // numerator
int deno; // denominator
Fraction() {
this(0, 1);
}
Fraction(int nume, int denu) {
this.nume = nume;
this.deno = denu;
reduce();
}
Fraction add(Fraction fo) {
int x;
int y = this.deno;
if (this.deno == fo.deno) {
x = this.nume + fo.nume;
} else {
x = this.nume * fo.deno + fo.nume * this.deno;
y = this.deno * fo.deno;
}
return new Fraction(x, y);
}
Fraction sub(Fraction fo) {
int x;
int y = this.deno;
if (this.deno == fo.deno) {
x = this.nume - fo.nume;
} else {
x = this.nume * fo.deno - fo.nume * this.deno;
y = this.deno * fo.deno;
}
return new Fraction(x, y);
}
Fraction mul(Fraction fo) {
int x = this.nume * fo.nume;
int y = this.deno * fo.deno;
return new Fraction(x, y);
}
Fraction div(Fraction fo) {
if (fo.nume == 0) {
System.out.println("Cannot be divided by zero!");
System.exit(-1);
}
int x = this.nume * fo.deno;
int y = this.deno * fo.nume;
return new Fraction(x, y);
}
int getMaxComFactor(int m, int n) {
if (nume == 0)
return 1;
if (m < n) {
m = m + n;
n = m - n;
m = m - n;
}
int r = m % n;
while (r != 0) {
m = n;
n = r;
r = m % n;
}
return n;
}
void reduce() {
if (deno == 0) {
System.out.println("The denominator cannot be zero!");
System.exit(-1);
}
int sign = 1;
if (nume * deno < 0) {
sign = -1;
}
int absNume = Math.abs(nume);
int absDenu = Math.abs(deno);
int maxFac = getMaxComFactor(absNume, absDenu);
nume = absNume / maxFac * sign;
deno = absDenu / maxFac;
}
@Override
public String toString() {
if (nume == 0)
return "0";
else if (nume == deno)
return "1";
else
return nume + "/" + deno;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
else if (obj.getClass() == Fraction.class) {
Fraction ft = (Fraction) obj;
if (ft.nume == this.nume && ft.deno == this.deno)
return true;
else
return false;
} else {
return false;
}
}
}
我该怎么改使得将分数以最简结果形式输出(所有的负分数输出时需用小括号括起来,分母为1时则以整数形式输出,分子为0时无论分母为何值均输出整数0