Write a class called Fraction which can be used to store an
Write a class called Fraction, which can be used to store an exact fraction. It must have: - A field to store the numerator - A field to store the denominator - A toString method that returns a neatly formatted String representing the fraction - An equals method that compares itself to another Fraction - An add method that adds itself to another Fraction and returns a new Fraction - Appropriate constructor and accessors as needed Write a program that asks the user to enter the numerators and denominators of two fractions and create corresponding Fraction objects. Check for valid input and a 0 denominator. Then output both Fractions (using your toString method implicitly), whether they are equal, and their sum. Note: You do not need to reduce your answer for the equals and sum. Name your main class Hw6pr2 and your file Hw6pr2.java. Submit all .java files
Solution
import java.util.Scanner;
public class Hw6pr2{
public int nu;
public int de;
// constructor
public Hw6pr2(int nu,int de){
this.nu = nu;
this.de = de;
}
// equals method to check whether two fractions are equal or not
public boolean equals(Hw6pr2 obj){
if(this.nu == obj.nu && this.de == obj.de){
return true;
}
else{
return false;
}
}
// add method to add two fractions.
public Hw6pr2 add(Hw6pr2 obj){
Hw6pr2 fract = new Hw6pr2(this.nu,this.de);
fract.nu = fract.de*obj.nu;
fract.de = fract.de*obj.de;
fract.nu = fract.nu + (this.nu*obj.de);
int i =2;
// divide both the numerator and denominator until all fractions are devided.
while(i<=fract.nu && i<=fract.de){
if(fract.nu%i == 0 && fract.de%i==0){
fract.nu = fract.nu/i;
fract.de = fract.de/i;
}
else{
i++;
}
}
return fract;
}
public int getNumerator(){
return this.nu;
}
public int getDenominator(){
return this.de;
}
public String toString(){
return nu+\"/\"+de;
}
// main method to test output
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
int d1,d2,n1,n2;
System.out.print(\"Enter numerator1:\");
n1 = sc.nextInt();
System.out.print(\"Enter denominator1:\");
d1 = sc.nextInt();
System.out.print(\"Enter numerator2:\");
n2 = sc.nextInt();
System.out.print(\"Enter denominator2:\");
d2 = sc.nextInt();
Hw6pr2 f1 = new Hw6pr2(n1,d1);
Hw6pr2 f2 = new Hw6pr2(n2,d2);
Hw6pr2 f3 = f1.add(f2);
System.out.println(\"f1 Equals f2: \"+f1.equals(f2));
System.out.println(\"Adding Fraction1 and Fraction2: \"+f3.toString());
}
}
/* sample output
Enter numerator1:1
Enter denominator1:1
Enter numerator2:2
Enter denominator2:2
f1 Equals f2: false
Adding Fraction1 and Fraction2: 2/1
*/

