Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Fraction {
- private long num1,den1;
- public Fraction(long num1, long den1) {
- this.num1 = num1;
- //check for divide by zero
- while (den1 == 0) {
- System.out.println("Denominator cannot be zero");
- //throw new IllegalArgumentException("Denominator is 0");
- System.out.println("Program is terminating");
- return;
- }
- this.den1 = den1;
- }
- public Fraction() {
- this.num1 = 0;
- this.den1 = 1;
- }
- private boolean checkIfReduced(Fraction F){
- for(long i = 1; i <= F.getDen1(); i++){
- if(F.getDen1() % i == 0){
- return false;
- }
- }
- return true;
- }
- private Fraction Reduce(Fraction F){
- //while not reduced
- while(checkIfReduced(F)){
- for(long i = 1; i <= F.getDen1(); i++){
- if(F.getDen1() % i == 0){
- F.setDen1(F.getDen1() / i);
- F.setNum1(F.getNum1() / i);
- }
- }
- }
- return F;
- }
- public Fraction Add( Fraction f){ //899/391
- //long num11, den22;
- long num11 = f.num1, den11 = f.den1;
- num11 = ( (this.num1 * f.den1) + (f.num1 * this.den1) );
- den11 =(this.den1 * f.den1);
- return new Fraction(num11,den11);
- }
- public Fraction subtract(Fraction f){
- long num11 = ( (this.getNum1() * f.getDen1()) - (f.getNum1() * this.getDen1()) );
- long den11 =(this.getDen1() * f.getDen1());
- return new Fraction(num11,den11);
- }
- public Fraction multiply(Fraction f){
- long den11 =(this.getDen1() * f.getDen1());
- long num11 = (this.getNum1() * f.getNum1());
- return new Fraction(num11,den11);
- }
- public Fraction divide(Fraction f){
- long den11 = this.den1 * f.num1;
- long num11 = this.num1 * f.den1;
- return new Fraction(num11,den11);
- }
- public void setNum1(long num1) {
- this.num1 = num1;
- }
- public void setDen1(long den1) {
- this.den1 = den1;
- }
- public long getNum1() {
- return num1;
- }
- public long getDen1() {
- return den1;
- }
- @Override
- public String toString(){
- Reduce(this);
- double result = (double)this.getNum1() / this.getDen1();
- System.out.println("Result: " + result);
- return this.getNum1() + " / " + this.getDen1();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement