Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Program Names: Rational.java and RationalDriver.java Define a class for rational

ID: 3691446 • Letter: P

Question

Program Names: Rational.java and RationalDriver.java Define a class for rational numbers. A rational number is a number that can be represented as the quotient of two integers. For example, 12, 34, and so forth are all rational numbers (by 12 and so forth, we mean the mathematical meaning of the fraction, not the integer division this expression would produce in a Java program.) Represent rational numbers as two values of type int, one for the numerator, and one for the denominator. Your class should have two instance variables of type int. The name of the class is Rational. Include a default constructor and an overloaded constructor with two arguments that are used to set the instance variables of an object of the Rational class to any two integer values. Note that the numerator, the denominator, or both may be negative. You should include a method to normalize the sign of the rational number so that the denominator is always positive and the numerator is either positive or negative. For example, after normalization, 4/-8 would be the same as –4/8. Define the following methods (using the names in parenthesis) for addition (add), subtraction (subtract), multiplication (multiply), and division (divide) of objects of your class, Rational. Each of these methods must accept a Rational object as the single parameter. Arithmetic operations on fractions are defined by the following rules: a/b + c/d = (ad + bc) / bd a/b –c/d = (ad-bc) / bd a/b * c/d = ac/db (a/b)/(c/d)=ad/bc, where c/d0 These are instance methods with a single argument that do not return a value. The result is a change in the state of the value of the data members of the calling object. For example, the add method (for addition) has a calling object and one argument. Therefore, if rationalNum1 has a numerator value of 1 and a denominator value of 2 and rationalNum2 has a numerator value of 1 and a denominator value of 4, the method call, rationalNum1.add(rationalNum2); changes the values of the instance variables of rationalNum1 so they represent the result of adding rationalNum2 to the original version of rationalNum1 (numerator is 3 and denominator is 4). CSC 201 Computer Science I Define observer (getter) and mutator (setter) methods. In addition, define the following method: • publicbooleanequals(Objectother) • publicStringtoString() Hint: Two rational numbers a/b and c/d are equal if a*d equals c*b. Guidelines for overriding the equals method: • Use the == operator to check if the argument is a reference to itself. • Use the instanceof operator to check if the argument has the correct data type. • Cast the argument to the correct type. • For each significant data member, test for equality. • Test these three properties: o Is it symmetric? o Is it transitive? o Is it consistent? Write a second class called RationalDriver containing a main method. Your main method will allow the user to thoroughly test all of the methods in your Rational class. The main method should take keyboard input from the user; instantiate two Rational objects, and then ask the user which operations to perform. Allow the user to continue performing operations on rational numbers until the user elects to quit. For example: Enter the numerator for rational number #1: Enter the denominator for rational number #1: Enter the numerator for rational number #2: Enter the denominator for rational number #2: Enter the corresponding number for the desired action, 1. Addition 2. Subtraction 3. Multiplication 4. Division 5. Test for Equality 6. Change 1st rational number 7. Change 2nd rational number 8. Exit Develop this program in stages: 1. Default and Parameterized Constructors 2. toString()to display fraction - print out fraction to test it 3. Normalize fraction after constructor executes 4. Implement method – print out results 5. Repeat.... for the remaining project requirements 6. Loop to allow multiple rational numbers to be input CSC 201 Computer Science I Your file names should be Rational.java and RationalDriver.java. Test your program with several different data sets. Document your tests on the attached table and submit the plan with copies of your source code files. Make sure your program is well documented - including the comment block header in the source code file; include a printHeading() method that is called from the main method; and follow all previous instructions about method and file names, identifiers, etc. Submit your source code to the assignment link in Blackboard by midnight on the due date.

Explanation / Answer

Rational.java

public class Rational{
   private int num, dnm; //Recommend using long for actual production
   private boolean hasZero = false;
   /**Default constructor sets the rational to 1/1*/
   public Rational(){
       setNum(1);
       setDnm(1);
   }
   /**Paramaterized constructor takes two ints, one for numerator and one for denominator
   * then calls normalize*/
   public Rational(int n, int d){
       setNum(n);
       setDnm(d);
       normalize();
   }
   /**Method to remove duplicate negatives, or move the negative to the numerator*/
   private void normalize(){
       if(getDnm() < 0){
           if(getNum() < 0){
               setNum(Math.abs(getNum()));
               setDnm(Math.abs(getDnm()));
           }
           else{
               setNum(0 - getNum());
               setDnm(Math.abs(getDnm()));
           }
       }
   }

   /**Method to get the numerator in the rational number*/
   public int getNum(){
       return num;
   }
   /**Method to get the denominator in the rational number*/
   public int getDnm(){
       return dnm;
   }
   /**Method to set the numerator in the rational number*/
   public void setNum(int n){
       num = n;
   }
   /**Method to set the denominator in the rational number*/
   public void setDnm(int d){
       dnm = d;
   }
   /**Method to check if an Object is of the Rational class*/
   public boolean isRational(Object obj){
       if(this == obj) return true;
       if(obj == null) return false;
       if(!(obj instanceof Rational)) return false;
       return true;
   }
   /**Method to compare two rational numbers for equality*/
   public boolean equals(Object other){
       if(!isRational(other)) return false;
       Rational rat2 = (Rational) other;
       if(getNum() * rat2.getDnm() == getDnm() * rat2.getNum()) return true;
       return false;
   }
   /**Method to display the two components of a rational number as a string*/
   public String toString(){
       return "(" + getNum() + "/" + getDnm() + ")";
   }

   /**Method to add two rational numbers*/
   public void add(Rational rat2){
       setNum(getNum() * rat2.getDnm() + getDnm() * rat2.getNum());
       setDnm(getDnm() * rat2.getDnm());
   }
   /**Method to subtract two rational numbers*/
   public void subtract(Rational rat2){
       setNum(getNum() * rat2.getDnm() - getDnm() * rat2.getNum());
       setDnm(getDnm() * rat2.getDnm());
   }
   /**Method to multiply two rational numbers*/
   public void multiply(Rational rat2){
       setNum(getNum() * rat2.getNum());
       setDnm(getDnm() * rat2.getDnm());
   }
   /**Method to divide two rational numbers*/
   public void divide(Rational rat2){
       setNum(getNum() * rat2.getDnm());
       setDnm(getDnm() * rat2.getNum());
   }
   /**This method implements the Euclidean algorithm to find the gcd*/
   public void factor(){
       normalize();//On the chance that the neg's will disappear
       int a = Math.abs(getNum());//We're looking for common factors, so don't care about sign here
       int b = Math.abs(getDnm());
       if(b > a){ //Set a to be the larger
           int larger = b;
           b = a;
           a = larger;
       }
       while(b != 0){
           int r = a % b;
           a = b;
           b = r;
       }
       setNum(getNum() / a);
       setDnm(getDnm() / a);
   }

   public static void main(String args[]){
       printHeading();
   }

}


RationalDriver.java
import java.lang.Character;
import java.util.Scanner;

/**This is the tester for the Rational class*/
public class HelloWorld{
   /**A method to display the menu to the user and receive the user's input
   * @return the user's selection*/
   public static char menu(){
       Scanner in = new Scanner(System.in);
       char choice = '5';
       System.out.println("Enter the corresponding number for the desired action");
       System.out.println("1. Addition");
       System.out.println("2. Subtraction");
       System.out.println("3. Multiplication");
       System.out.println("4. Division");
       System.out.println("5. Test for Equality");
       System.out.println("6. Change 1st rational number");
       System.out.println("7. Change 2nd rational number");
       System.out.println("(Q/q/X/x/Y/y) to exit");
       System.out.println("Any other key for menu");
       choice = in.next().charAt(0);
       return choice;
   }
   /**Establish two rational objects and allow the user to perform basic arithmetic
   * operations and directly modify or compare the rational numbers*/
   public static void main (String args[]){
       Rational.printHeading();
       int num = 1, dnm = 1;
       char choice = 'm';
       Scanner in = new Scanner(System.in);
       Rational r1 = new Rational(), r2 = new Rational();
       r1.setNum(nonZero('1', "numerator"));
       r1.setDnm(nonZero('1', "denominator"));
       r1.factor();
       System.out.println("Rational Number #1: " + r1.toString());

       r2.setNum(nonZero('2', "numerator"));
       r2.setDnm(nonZero('2', "denominator"));
       r2.factor();
       System.out.println("Rational Number #2: " + r2.toString());
       do{
           if(choice < '1' || choice > '7') choice = menu();
           if(choice >= '1' && choice <= '4'){
               System.out.print(r1.toString());
               if(choice == '1'){
                   System.out.println(" + " + r2.toString() + " = ");
                   r1.add(r2);
               }  
               else if(choice == '2'){
                   System.out.println(" - " + r2.toString() + " = ");
                   r1.subtract(r2);
               }  
               else if(choice == '3'){
                   System.out.println(" * " + r2.toString() + " = ");
                   r1.multiply(r2);
               }  
               else if(choice == '4'){
                   System.out.println(" / " + r2.toString() + " = ");
                   r1.divide(r2);
               }  
               r1.factor();
               System.out.print(r1.toString() + " ");
           }
           else if(choice == '5'){
               System.out.println(r1.toString() + " = " + r2.toString() + " : " + r1.equals(r2));
           }  
           else if(choice == '6'){
               r1.setNum(nonZero('1', " Enter the numerator for rational number"));
               r1.setDnm(nonZero('1', " Enter the denominator for rational number"));
               r1.factor();
               System.out.println("Rational Number #1: " + r1.toString());
           }  
           else if(choice == '7'){
               r2.setNum(nonZero('2', "Enter the numerator for rational number"));
               r2.setDnm(nonZero('2', "Enter the denominator for rational number"));
               r2.factor();
               System.out.println("Rational Number #2: " + r2.toString());
           }  
           System.out.print("Select (m)enu entry or exit: ");
           choice = in.next().charAt(0);
       }while(choice != 'y' && choice != 'Y' && choice != 'q' && choice != 'Q' && choice != 'x' && choice != 'X');
   }

   /**This method prompts the user to input a nonzero number
   * @param char which rational number to modify
   * @param String which part of the rational number to modify
   * @return the value recieved from the user
   */
   public static int nonZero(char first, String selection){
       Scanner in = new Scanner(System.in);
       int number = 0;
       do{
           System.out.print("Enter the " + selection + " for rational number #" + first + ": ");
           while(!in.hasNextInt())   in.next();
           number = in.nextInt();
           if(number == 0)   System.out.println("Number must be nonzero.");
       }while(number == 0);
       return number;
   }
}


sample output

Enter the numerator for rational number #1: 2                                                                                                               
Enter the denominator for rational number #1: 2                                                                                                             
Rational Number #1: (1/1)                                                                                                                                   
Enter the numerator for rational number #2: 4                                                                                                               
Enter the denominator for rational number #2: 3                                                                                                             
Rational Number #2: (4/3)                                                                                                                                   
Rational Number #2: (4/3)                                                                                                                                   
Enter the corresponding number for the desired action                                                                                                       
1. Addition                                                                                                                                                 
2. Subtraction                                                                                                                                              
3. Multiplication                                                                                                                                           
4. Division                                                                                                                                                 
5. Test for Equality                                                                                                                                        
6. Change 1st rational number                                                                                                                               
7. Change 2nd rational number                                                                                                                               
(Q/q/X/x/Y/y) to exit                                                                                                                                       
Any other key for menu                                                                                                                                      
1                                                                                                                                                           
(1/1) + (4/3) =                                                                                                                                             
(7/3)                                                                                                                                                       
Select (m)enu entry or exit: q                                                                                                                              

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote