/*! This file is auto-generated */ .wp-block-button__link{color:#fff;background-color:#32373c;border-radius:9999px;box-shadow:none;text-decoration:none;padding:calc(.667em + 2px) calc(1.333em + 2px);font-size:1.125em}.wp-block-file__button{background:#32373c;color:#fff;text-decoration:none} Problem 17 \((\text {Rational Numbers})\) C... [FREE SOLUTION] | 91Ó°ÊÓ

91Ó°ÊÓ

\((\text {Rational Numbers})\) Create a class called Rational for performing arithmetic with fractions. Write a program to test your class. Use integer variables to represent the private instance variables of the class - the numerator and the denominator. Provide a constructor that enables an object of this class to be initialized when it is declared. The constructor should store the fraction in reduced form. The fraction \\[ 2 / 4 \\] is equivalent to \(1 / 2\) and would be stored in the object as 1 in the numerator and 2 in the denominator. Provide a no-argument constructor with default values in case no initializers are provided. Provide public methods that perform each of the following operations: a) Add two Rational numbers: The result of the addition should be stored in reduced form. b) Subtract two Rational numbers: The result of the subtraction should be stored in reduced form. c) Multiply two Rational numbers: The result of the multiplication should be stored in reduced form. d) Divide two Rational numbers: The result of the division should be stored in reduced form. e) Print Rational numbers in the form a/b, where a is the numerator and b is the denom- inator. f) Print Rational numbers in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.)

Short Answer

Expert verified
Define a `Rational` class with methods for arithmetic operations and printing in fractional and decimal form. Include constructors and simplify fractions upon each operation.

Step by step solution

01

Define the Rational Class

Create a class named `Rational` with private instance variables `numerator` and `denominator`. These will be used to store the numerator and denominator of the rational number.
02

Implement Constructors

Create a constructor that accepts two integers, `num` and `denom`, and reduces them to their simplest form. Also, implement a no-argument constructor that sets the rational number to a default value like \(0/1\).
03

Simplify the Fraction

Implement a private method named `reduce()` that calculates and applies the greatest common divisor (GCD) to simplify the fraction. Use the Euclidean algorithm to find the GCD.
04

Addition Method

Define a method `add(Rational r)` that calculates the sum of the current Rational object with another. Use \( \frac{a}{b} + \frac{c}{d} = \frac{ad + bc}{bd} \) to compute the new numerator and denominator, then simplify using `reduce()`.
05

Subtraction Method

Create a method `subtract(Rational r)` following a similar logic as addition: \( \frac{a}{b} - \frac{c}{d} = \frac{ad - bc}{bd} \). Simplify the result with `reduce()`.
06

Multiplication Method

Design a method `multiply(Rational r)` that multiplies the current Rational object with another: \( \frac{a}{b} \times \frac{c}{d} = \frac{ac}{bd} \). Simplify the product using `reduce()`.
07

Division Method

Create a method `divide(Rational r)` by multiplying with the reciprocal of another Rational object: \( \frac{a}{b} \div \frac{c}{d} = \frac{a \cdot d}{b \cdot c} \). Call `reduce()` to simplify the result.
08

Print Method for Fraction

Implement a method `printFraction()` that returns a string of the form `"a/b"`, representing the fraction (handle special cases such as denominators of 1 to return just the numerator).
09

Print Method for Decimal

Develop a method `printDecimal(int precision)` that converts the fraction to decimal form with the specified precision, using string formatting for the correct number of decimal places.
10

Test the Class

Create a separate test class with a `main` method that creates various `Rational` instances. Call the methods to test addition, subtraction, multiplication, division, and both print methods to ensure correct functionality.

Unlock Step-by-Step Solutions & Ace Your Exams!

  • Full Textbook Solutions

    Get detailed explanations and key concepts

  • Unlimited Al creation

    Al flashcards, explanations, exams and more...

  • Ads-free access

    To over 500 millions flashcards

  • Money-back guarantee

    We refund you if you fail your exam.

Over 30 million students worldwide already upgrade their learning with 91Ó°ÊÓ!

Key Concepts

These are the key concepts you need to understand to accurately answer the question.

Java classes
In Java, classes are foundational building blocks of object-oriented programming. A class serves as a blueprint for creating objects, allowing developers to define the properties and behaviors that the objects, often referred to as instances, will have. For example, in our `Rational` class, this concept is applied to handle operations on rational numbers (fractions).

The class contains instance variables for the numerator and denominator, which hold the essential state of a fraction. By encapsulating the data within the class, we ensure that these properties can only be accessed and modified through defined methods.

By organizing code into classes, we create reusable components that can interact with each other within a program. This makes Java classes vital for building scalable and maintainable software applications.
Fraction arithmetic
Fraction arithmetic involves operations such as addition, subtraction, multiplication, and division performed on fractions. This is an essential part of math that can also be implemented programmatically. In our `Rational` class example, we have methods for each type of fraction operation.

  • **Addition** is performed using the formula \( \frac{a}{b} + \frac{c}{d} = \frac{ad + bc}{bd} \).
  • **Subtraction** is managed similarly: \( \frac{a}{b} - \frac{c}{d} = \frac{ad - bc}{bd} \).
  • **Multiplication** is straightforward: \( \frac{a}{b} \times \frac{c}{d} = \frac{ac}{bd} \).
  • **Division** involves reciprocation: \( \frac{a}{b} \div \frac{c}{d} = \frac{a \cdot d}{b \cdot c} \).
After each operation, it is crucial to reduce the result to its simplest form to ensure the fraction is appropriately represented.
Instance variables
Instance variables are non-static variables defined within a class, and each instance of the class has its own copy of them. In the context of our `Rational` class, the numerator and denominator are private instance variables.

These variables are critical because they store the specific state of a fraction for each object, meaning that each `Rational` object can represent different fractions. This encapsulation is a key principle of object-oriented programming as it helps maintain data integrity by controlling how data is accessed and modified.

By declaring them private, we ensure that these variables cannot be directly accessed from outside the class. Instead, they require methods such as constructors and other member functions to be used, preserving the internal consistency of the object's state.
Constructors in Java
Constructors in Java play a crucial role in object creation by initializing new instances of a class with specific attributes. In the `Rational` class, there are two constructors: one with parameters and a no-argument default constructor.

The parameterized constructor allows for initial values for the numerator and denominator to be set and also calls a method to reduce the fraction to its simplest form. This ensures that the object is always in a valid state with its attributes set correctly after creation.

The default constructor provides a way to create a `Rational` object without initial values, usually setting the fraction to a default like 0/1. Constructors ensure that the creation of an object is streamlined and efficient, maintaining control over how objects are initialized in Java.

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Most popular questions from this chapter

(Date Class) Create class Date with the following capabilities: a) Output the date in multiple formats, such as MM/DD/YYYY June \(14, \quad 1992\) DDD YYYY b) Use overloaded constructors to create Date objects initialized with dates of the formats in part (a). In the first case the constructor should receive three integer values. In the second case it should receive a String and two integer values. In the third case it should receive two integer values, the first of which represents the day number in the year. \([\text {Hint: }\) To convert the string representation of the month to a numeric value, compare strings using the equals method. For example, if \(s 1\) and \(s 2\) are strings, the method call s1.equals \((s 2)\) returns true if the strings are identical and otherwise returns false.

\((\text { Enhancing Class Date})\) Modify class Date of Fig. 8.7 to perform error checking on the initializer values for instance variables month, day and year (currently it validates only the month and day). Provide a method nextDay to increment the day by one. The Date object should always remain in a consistent state. Write a program that rests the nextDay method in a loop that prints the date during each iteration of the loop to illustrate that the nextDay method works correctly. Test the following cases: a) incrementing into the next month and b) incrementing into the next year.

Write an enum type TrafficLight, whose constants (RED, GREEN, YELLOW) take one parameter - the duration of the light. Write a program to test the TrafficLight enum so that it displays the enum constants and their durations.

What happens when a return type, even void, is specified for a constructor?

(Returning Error Indicators from Metbods) Modify the set methods in class Time2 of Fig. 8.5 to return appropriate error values if an attempt is made to set one of the instance variables hour, minute or second of an object of class Time to an invalid value. [Hint: Use boolean return types on cach method.] Write a program that tests these new set methods and outputs error messages when incorrect values are supplied.

See all solutions

Recommended explanations on Computer Science Textbooks

View all explanations

What do you think about this solution?

We value your feedback to improve our textbook solutions.

Study anywhere. Anytime. Across all devices.