Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- class Fraction {
- /* private for numerator and denominator so that they cannot be directly accessed outside Fraction */
- private int numerator;
- private int denominator;
- static int count = 0; //To get count of total Fractions in the programme, by default public (Even though not specified).
- /* Default constructor that does not initialize this Fraction */
- public Fraction() {
- }
- public Fraction(int n , int d) {
- this.numerator = n;
- this.denominator = d;
- count++;
- }
- /* To get the value of denominator outside Fraction */
- public int getDenominator() {
- return denominator;
- }
- /* To get the value of numerator outside Fraction */
- public int getNumerator() {
- return numerator;
- }
- /* To set the value of numerator from outside Fraction */
- public void setNumerator(int n) {
- this.numerator = n;
- }
- /* To set the value of denominator from outside Fraction */
- public void setDenominator(int d) {
- this.denominator = d;
- }
- /* Gets inherited by MixedFraction */
- public void printFraction() {
- System.out.println(numerator + "/" + denominator);
- }
- public static void printCount() {
- System.out.println(count);
- }
- public static Fraction add(Fraction a , Fraction b) {
- Fraction fraction = new Fraction();
- if (a.getDenominator() == b.getDenominator()) {
- fraction.setDenominator(a.getDenominator()); //Any one of a or b will work
- fraction.setNumerator(a.getNumerator() + b.getNumerator());
- }
- else {
- fraction.setDenominator(a.getDenominator() * b.getDenominator());
- fraction.setNumerator(a.getNumerator() * b.getDenominator() + b.getNumerator() * a.getDenominator());
- }
- return fraction;
- }
- }
- class MixedFraction extends Fraction {
- private int wholenumber;
- public MixedFraction(int n , int d , int w) {
- //super(n,d); This way we can initialize the Fraction inside the MixedFraction by simply calling the constructor of Fraction(n,d)
- this.wholenumber = w;
- setNumerator(n);
- setDenominator(d);
- }
- // Overriden function. When you call printFraction() from object of MixedFraction, it will use only this one, and not the one set in Fraction.
- public void printFraction() {
- System.out.println(this.wholenumber + " " + getNumerator() + "/" + getDenominator());
- }
- }
- public class FractionProgram {
- public static void main(String[] args) {
- int n , d , w;
- Scanner scan = new Scanner(System.in);
- System.out.println("Enter Numerator, Denominator and Whole Number: ");
- n = scan.nextInt();
- d = scan.nextInt();
- w = scan.nextInt();
- MixedFraction fraction = new MixedFraction(n , d, w);
- fraction.printFraction(); //Overriden function
- Fraction.add(new Fraction(4,5) , new Fraction(3,4)).printFraction(); //Takes two fractions 4/5 and 3/4, adds them and prints them. Static function
- }
- }
Add Comment
Please, Sign In to add comment