pku 3979 分数分数分数!! 2011/09/03

Javaです。
3979 -- 分数加减法
ぜんぜん難しくない問題なはずですが、いろいろ失敗。 scannerを使ってのEOFはscanner.hasNext()を使えばOKなようです。
で、いろいろwrong answerだった理由は、1/2+1/2とか20/2-10/2で解答を分数で出力していたから。

package p3979; import java.math.BigInteger; import java.util.Scanner; public class Main { static class A { // numerator BigInteger n; // denominator BigInteger d; public A(int n, int d) { this.n = BigInteger.valueOf(n); this.d = BigInteger.valueOf(d); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String line = scanner.next("[0-9]*/[0-9]*[+-][0-9]*/[0-9]*"); char c; // + or - if (line.contains("+")) { c = '+'; } else { c = '-'; } String[] ss = line.split("[+-]"); A l = A(ss[0]); A r = A(ss[1]); solve(c, l, r); } } static public BigInteger gcd(BigInteger l, BigInteger r) { return l.gcd(r); } static public BigInteger lcm(BigInteger l, BigInteger r) { return l.multiply(r).divide(gcd(l, r)); } static void solve(char c, A l, A r) { // 最小公倍数 BigInteger b = lcm(l.d, r.d); BigInteger n1 = b.divide(l.d).multiply(l.n);// L BigInteger n2 = b.divide(r.d).multiply(r.n);// R // 演算 BigInteger c1 = c == '+' ? n1.add(n2) : n1.subtract(n2); if (c1.equals(BigInteger.ZERO)) { System.out.println("0"); return; } if (c1.equals(b)) { System.out.println("1"); return; } // 割れなくなるまで BigInteger b2 = gcd(c1, b); if ((b.divide(b2)).intValue() == 1) { System.out.println((c1.divide(b2)).intValue()); return; } // System.out.println(b2); System.out.printf("%d/%d%n", (c1.divide(b2)).intValue(), (b.divide(b2)).intValue()); return; } static A A(String s) { String[] ss = s.split("/"); return new A(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])); } }

: