/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package prueba1;
/**
*
* @author kirito
*/
public class Fraccion {
private int num;
private int den;
public Fraccion() {
this.den = 1;
this.num = 0;
}
public Fraccion(int num, int den) {
this.den = den;
this.num = num;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getDen() {
return den;
}
public void setDen(int den) {
this.den = den;
}
public static Fraccion obtener(String cad) throws NumberFormatException {
System.out.println("Fraccion obteniendo");
Fraccion temp = new Fraccion();
int i = cad.indexOf("/");
String num = cad.substring(0, i);
temp.setNum(Integer.parseInt(num));
num = cad.substring(i + 1, cad.length());
if (Integer.parseInt(num) == 0) {
throw new NumberFormatException("Denominador=0");
} else {
temp.setDen(Integer.parseInt(num));
}
System.out.println("fin Fraccion obteniendo " + temp.getNum() + "/" + temp.getDen());
return temp;
}
public void reducir() {
int mayor = num > den ? num : den;
for (int i = mayor; i > 0; i--) {
if (den % i == 0 && num % i == 0) {
this.num /= i;
this.den /= i;
}
}
}
public static Fraccion suma(Fraccion x, Fraccion y) {
System.out.println("Fraccion suma");
Fraccion temp = new Fraccion();
temp.setNum((x.getNum() * y.getDen()) + (x.getDen() * y.getNum()));
temp.setDen(x.getDen() * y.getDen());
System.out.println("fin Fraccion suma " + temp.getNum() + "/" + temp.getDen());
temp.reducir();
return temp;
}
public static Fraccion resta(Fraccion x, Fraccion y) {
System.out.println("Fraccion suma");
Fraccion temp = new Fraccion();
temp.setNum((x.getNum() * y.getDen()) - (x.getDen() * y.getNum()));
temp.setDen(x.getDen() * y.getDen());
System.out.println("fin Fraccion suma " + temp.getNum() + "/" + temp.getDen());
temp.reducir();
return temp;
}
public static Fraccion multiplicacion(Fraccion x, Fraccion y){
Fraccion temp = new Fraccion();
temp.setDen(x.getDen()*y.getDen());
temp.setNum(x.getNum()*y.getNum());
temp.reducir();
return temp;
}
public static Fraccion divicion(Fraccion x, Fraccion y){
Fraccion temp = new Fraccion();
temp.setNum(x.getNum()*y.getDen());
temp.setDen(x.getDen()*y.getNum());
temp.reducir();
return temp;
}
@Override
public String toString() {
if (this.num > 0) {
return this.num == this.den ? 1 + "" : this.num + "/" + this.den;
} else {
return 0 + "";
}
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.