Is my implementation of a Rational number using classes acceptable?

331 Views Asked by At

I am trying to finish my rational class for java and everywhere I have looked to make it finished doesn't have it near the same. I know I could use others programs that where made but the ones I have seen don't have it for where you put the input in when you run the program. This is the code I have so far

import java.util.Scanner;


public class Lab09ast
{
    private static int num, den;   // numerator and denominator of the rational number

    public static void main (String[] args)
    {
        enterData();
        Rational r = new Rational(num,den);
        r.displayData();
    }

    public static void enterData()
    {
        Scanner input = new Scanner(System.in);
        System.out.print("\nEnter the numerator ----> ");
        num = input.nextInt();
        System.out.print("\nEnter the denominator --> ");
        den = input.nextInt();
    }
}



class Rational
{

    public void displayData()
    {
        System.out.println();
        System.out.println(getNum() + "/" + getDen() + " equals " + getDecimal());
        System.out.println();
    }

    private void getGCF(int n1,int n2)
    {
        int rem = 0;
        do
        {
            rem = n1 % n2;
            if (rem == 0)
                gcf = n2;
            else
            {
                n1 = n2;
                n2 = rem;
            }
        }
        while (rem != 0);
    }
}
1

There are 1 best solutions below

0
On

Member variables num and den (numerator and denominator) are in class Lab09ast. These should be in class Rational. Do you understand the concepts of classes and objects?

It's logical that a Rational object, which you make from the class Rational, has member variables for the numerator and denominator.

Also, those member variables must not be static. See Understanding Class Members to learn what static means and why it is not appropriate for these member variables.

The methods getNum() and getDen() should return the values of the num and den member variables, and should also be in class Rational.

Class Rational should also have a constructor that takes two arguments, for the numerator and denominator. You're already calling that constructor in the main method of class Lab09ast, but it's not in your class Rational yet.