Question 5.3: Implement the following class ‘Fraction’ and test its methods.
void add(Fraction fraction)
Adds two Fraction objects and stores the result into calling object. This is how addition is performed for fractions: 1 / 4 + 3 / 5 = 1 * 5 + 3 * 4 / 4 * 5 = 17 / 20
String toString()
Returns the value of the fraction in 1 / 2 format where 1 is numerator and 2 is denominator.
Now write a test program, take two Fraction objects. Print both of them. Test add, sub, multiplication and division
methods. Print calling object after each method call.
Solution:
//Fraction class
public class Fraction {
private int number;
private int denominator;
Fraction(int number, int denominator) {
this.number = number;
this.denominator = denominator;
}
public void setnumber(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
public void setdenominator(int denominator) {
this.denominator = denominator;
}
public int getdenominator() {
return denominator;
}
public String toString() {
return number + "/" + denominator;
}
public void add(Fraction fraction) {
int sum1 = (number * fraction.getdenominator() + denominator * fraction.getNumber());
int sum2 = denominator * fraction.getdenominator();
System.out.println(sum1 + "/" + sum2);
}
public void subject(Fraction fraction) {
int subject1 = (number * fraction.getdenominator() - denominator * fraction.getNumber());
int subject2 = denominator * fraction.getdenominator();
System.out.println(subject1 + "/" + subject2);
}
public void multiplication(Fraction fraction) {
int multiplication1 = number * fraction.getNumber();
int multiplication2 = denominator * fraction.getdenominator();
System.out.println(multiplication1 + "/" + multiplication2);
}
public void division(Fraction fraction) {
int division1 = number * fraction.getdenominator();
int division2 = denominator * fraction.getNumber();
System.out.println(division1 + "/" + division2);
}
}
//Main Class
public class testFraction {
public static void main(String[] args) {
Fraction input1 = new Fraction(1, 4);
Fraction input2 = new Fraction(3, 5);
System.out.println(input1.toString());
System.out.println(input2.toString());
input1.add(input2);
input1.subject(input2);
input1.multiplication(input2);
input1.division(input2);
}
}