1. Write a class named Rational to represent Rational numbers. The UML represent
ID: 3634311 • Letter: 1
Question
1. Write a class named Rational to represent Rational numbers. The UML representation of the class is:Rational
__________________________________________
-numerator: long
-denominator: long
__________________________________________
+Rational()
+Rational(long numerator, long Denomination)
+getNumerator(): long
+getDenominator(): long
+setNumerator(num:long): void
+add(Rational secondRational): Rational
+multiply(Rational secondeRational): Rational
+subtract(Rational secondeRational): Rational
+divide(Rational secondeRational): Rational
+equals(r: Rational): Boolean
+compareTo(r: Rational): long
+toString(): String
-gcd(num: long, den:long) : long
• Default value for a Rational obect is 0/1
• Rational objects must be in reduced form
• Rational objects should not be modified by an of the methods
• toString() format is “numerator/denominator”
2. Given n, write a program that will compute the following summation series using the Rational class. Output should as follows:
1/1+1/2+1/3………..+1/n=result
3. Write a program to do the following:
a) Generate a list of ten random rational numbers(numerator and denominator should be in range of 1 to 100 inclusively)
b) Print the list
c) Find the maximum value in the list
d) Print the result.
Explanation / Answer
Dear User, Summation series using the Rational class: //Header file section import java.io.*; import java.util.*; import java.text.*; //class declartion class ComputeSum { // Main method. public static void main(String[] args) { try { DecimalFormat df = new DecimalFormat("##.##"); // Taking the input from the user. System.out.print("Enter the value of n : "); // Creating the Scanner object. Scanner input = new Scanner(System.in); String str = input.next(); int n = Integer.parseInt(str); if(n < 1) { System.out.print("Invalid Entry"); System.exit(0); } // Calling the method to compute the sum. double sum = add(n); // Displaying the sum. System.out.print("The sum is : " +df.format(sum)); } catch(Exception e) { System.out.print("Exception has occured. Program will exit"); System.exit(0); } } // Method to compute the sum. static double add(int n) { double s; if (n == 1) return (1.0/2.0); else s = (n / (n + 1.0)) + add(n-1); return s; } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.