Question: Please help in Java: Create a fraction class. This will have two attributes, a numerator and a denominator, both int. This class will have: -constructors

Please help in Java:

Create a fraction class. This will have two attributes, a numerator and a denominator, both int. This class will have:

-constructors

-accessors and mutators (for the attributes)

-a toString method which will allow us to print the fraction in the form 3/4

-an Add method so we can add two fractions

-a subtract method (subtracts one fraction from the other)

-a multiply method (multiply two fractions)

-a divide method (divides one fraction by the other)

This is what I have so far:

public static class Fraction {

private int numerator;

private int denominator;

public Fraction() {

numerator=0;

denominator=0;

}

public Fraction(int n, int d){

this.numerator=n;

denominator=d;

if (d!=0){

this.denominator = d;

}

else {

System.out.println("Cant be 0!!");

}

}

/*public void setNum(int n){

numerator=n;

}

public void setDen(int d){

denominator=d;

}

public int getNum(){

return numerator;

}

public int getDen(){

return denominator;

}*/

//add

public String Add(Fraction x){

int a=this.numerator;

int b=this.denominator;

int c=x.numerator;

int d=x.denominator;

return ((a*d)+(c*b))+"/"+(b*d);

}

//subtract

public String Subtract(Fraction x){

int a=this.numerator;

int b=this.denominator;

int c=x.numerator;

int d=x.denominator;

return ((a*d)-(c*b))+"/"+(b*d);

}

//multiply

public String Multiply(Fraction x){

int a=this.numerator;

int b=this.denominator;

int c=x.numerator;

int d=x.denominator;

return (a*c)+"/"+(b*d);

}

//divide

public String Divide(Fraction x){

int a=this.numerator;

int b=this.denominator;

int c=x.numerator;

int d=x.denominator;

return (a*d)+"/"+(b*c);

}

//toString

public String toString() {

return numerator+"/"+denominator;

}

public static void main(String[] args) {

}

}

}

Thanks!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!