+
+class CeroDenExc extends Exception {
+
+ private int num;
+
+ public int getNum() {
+ return num;
+ }
+
+ public void setNum(int n) {
+ num = n;
+ }
+
+ public CeroDenExc(int num) {
+ setNum(num);
+ }
+
+ public String toString() {
+ return "Division por 0 (numerador = " + getNum() + ")";
+ }
+
+}
+
+interface OperFrac {
+
+ public Fraccion mas(Fraccion f);
+
+ public Fraccion menos(Fraccion f);
+
+}
+
+interface ComparaFrac {
+
+ public int compareTo(Fraccion f);
+
+}
+
+class Fraccion implements OperFrac, ComparaFrac {
+
+ private int num;
+ private int den;
+
+ public int getNum() {
+ return num;
+ }
+
+ public int getDen() {
+ return den;
+ }
+
+ public void setNum(int n) {
+ num = n;
+ }
+
+ public void setDen(int d) {
+ den = d;
+ }
+
+ public Fraccion() {
+ setNum(1);
+ setDen(1);
+ }
+
+ public Fraccion(int num, int den) throws CeroDenExc {
+ if (den == 0)
+ throw new CeroDenExc(num);
+ setNum(num);
+ setDen(den);
+ normalizar();
+ }
+
+ public Fraccion(Fraccion f) {
+ setNum(f.num);
+ setDen(f.den);
+ }
+
+ public String toString() {
+ if (getNum() == 0)
+ return "0";
+ if (getDen() == 1)
+ return "" + getNum();
+ else
+ return getNum() + "/" + getDen();
+ }
+
+ public Fraccion mas(Fraccion f) {
+ try {
+ return new Fraccion(getNum() * f.getDen() + f.getNum() * getDen(),
+ getDen() * f.getDen());
+ } catch (CeroDenExc e) {
+ return new Fraccion(); // Nunca deberia pasar
+ }
+ }
+
+ public Fraccion menos(Fraccion f) {
+ try {
+ return new Fraccion(getNum() * f.getDen() - f.getNum() * getDen(),
+ getDen() * f.getDen());
+ } catch (CeroDenExc e) {
+ return new Fraccion(); // Nunca deberia pasar
+ }
+ }
+
+ public int compareTo(Fraccion f) {
+ if (getNum() * f.getDen() > getDen() * f.getNum())
+ return 1;
+ if (getNum() * f.getDen() < getDen() * f.getNum())
+ return -1;
+ return 0;
+ }
+
+ private static int mcd(int num, int den) {
+ int max = Math.abs(Math.max(num, den));
+ int min = Math.abs(Math.min(num, den));
+ if (max % min == 0)
+ return min;
+ else
+ return mcd(min, max % min);
+ }
+
+ private void normalizar() {
+ int d = mcd(getNum(), getDen());
+ setNum(getNum() / d);
+ setDen(getDen() / d);
+ }
+
+ // Test
+ public static void main(String args[]) throws CeroDenExc {
+ try {
+ Fraccion f = new Fraccion(10, 0);
+ } catch (CeroDenExc e) {
+ System.out.println("Ahhh! Esta rota la fraccion!"
+ + " tiene numerador " + e.getNum() + " y divisor 0");
+ }
+ Fraccion f1 = new Fraccion(2, 10);
+ System.out.println("f1 = " + f1);
+ System.out.println("f1 + f1 = " + f1.mas(f1));
+ Fraccion f3 = f1.menos(new Fraccion(100, 4));
+ System.out.println("f3 = " + f3);
+ System.out.println("f3 comparado a f1 = " + f3.compareTo(f1));
+ //System.out.println("Java esta roto en el manejo de excepciones!!!");
+ }
+
+}
+
+// vim: set et sw=4 sts=4 :