Add a toString() method to Fraction class that returns the fraction as a
String in the form "x / y", where x and y are numerator and denominator
respectively. As the method does not do any display itself, the output can be done by a client program that calls the method in an output statement. Use client program to test this functionality; i.e. provide an output statement to display a fraction as its String representation.
class Fraction2
{
private int n, d;
public Fraction()
{
this.n = this.d = 0; //Initialize the values
}
public Fraction(int n, int d)
{
this.n = n; //Initialize the variables
this.d = d;
}
//Define the getter function getNum() that returns the numerator
public int getNum()
{
//Returns numerator
return n;
}
//Define the getter function getDen() that returns the denominator
public int getDen()
{
//Returns denominator
return d;
}
//Define the boolean function isZero() that returns 0 if numerator is 0 and denominator is not equals to zero
public boolean isZero()
{
return(getNum() == 0 && getDen() != 0);
}
public boolean isequals(Object c)
{
Fraction f = (Fraction) c;
return(Integer.compare(n,f.n))==0 && (Integer.compare(d,f.d)==0);
}
//Define the function getSimplifiedFraction() that returns the simplified fraction
public String getSimplifiedFraction()
{
//Decalre the string variable result to store the result
String result = "";
//if the numerator and denominator both are zero
if(getNum() == 0 && getDen() == 0)
//result is zero
result = "0";
//if the numerator is zero and denominator is non-zero
else if(isZero())
//result is zero
result = "0";
//if the numerator is non-zero and denominator is zero
else if(getNum() != 0 && getDen() == 0)
//result is Undefined
result = "Undefined";
//for a defined and non-zero fraction
else
{
//if the remainder is zero
if(getNum() % getDen() == 0)
result = (getNum() / getDen()) + "";
//if the numerator and denominator both are greater than zero
else if(getNum() < 0 && getDen() < 0)
result = (getNum() * -1) + "/" + (getDen() * -1);
//if any of them is zero
else if(getNum() < 0 || getDen() < 0)
{
//if the numerator is greater than zero
if(getNum() < 0)
result = "-" + (getNum() * -1) + "/" + getDen(); // appending a sign.
//if the denominator is zero
else
result = "-" + getNum() + "/" + (getDen() * -1); // appending a sign.
}
//both are non-zero
else
result = (getNum() + "/" + getDen());
}
//return the result
return result;
}
//Define the method display() that displays the resultant fraction
public void display()
{
//Call and display the fraction
System.out.println(getSimplifiedFraction());
}
public Fraction add(Fraction rhs) {
Fraction sum = new Fraction();
sum.d = d * rhs.d;
sum.n = n * rhs.d + d * rhs.n;
sum.simplify();
return sum;
}
private void simplify()
{
int a,b;
if(Math.abs(n) > Math.abs(d))
{
a = Math.abs(n);
b = Math.abs(d);
}
else
{
a = Math.abs(d);
b = Math.abs(n);
}
int r = a%b;
while(r != 0)
{
a = b;
b = r;
r = a%b;
}
//divide numerator and denominator by b
n /= b;
d /= b;
}
Trending nowThis is a popular solution!
Step by stepSolved in 3 steps with 1 images
- Write a public int method named initialNumberOfSticks which takes two int parameters named max_sticks and min_sticks and returns a random integer value between max_sticks and min_sticks (inclusive). You will create a new instance of the Random class and call it r. Use the nextInt method of r to a get random value within a desired range and use it to compute the value that will be returned. Your method must be a syntactically correct Java method.arrow_forwardCreate the compareTo method for a class that represents an individual whose first and last names are stored as two Strings. In an alphabetical list of people with last names first and then first names, one individual is "less than" another if they come before the other.(as is typical).arrow_forwardThe goal of this coding exercise is to create two classes BookstoreBook and LibraryBook. Both classes have these attributes: author: Stringtiltle: Stringisbn : String- The BookstoreBook has an additional data member to store the price of the book, and whether the book is on sale or not. If a bookstore book is on sale, we need to add the reduction percentage (like 20% off...etc). For a LibraryBook, we add the call number (that tells you where the book is in the library) as a string. The call number is automatically generated by the following procedure:The call number is a string with the format xx.yyy.c, where xx is the floor number that is randomly assigned (our library has 99 floors), yyy are the first three letters of the author’s name (we assume that all names are at least three letters long), and c is the last character of the isbn.- In each of the classes, add the setters, the getters, at least three constructors (of your choosing) and override the toString method (see samplerun…arrow_forward
- Write a method for the farmer class that allows a farmer object to pet all cows on the farm. Do not use arrays.arrow_forwardWrite a java code for this. Strings Read the paragraph and encrypt the content using the following rules; "The String, StringBuffer, and StringBuilder classes are defined in java.lang. Thus, they are available to all programs automatically. All are declared final, which means that none of these classes may be subclassed. This allows certain optimizations that increase performance to take place on common string operations. All three implement the CharSequence interface." RULES The words ‘the’, ‘and’, and ‘for’ should be replaced by their reverse strings in upper case letters (use predefined functions reverse() and toupper()) The first occurrence of the word ‘are’ should be replaced by ‘AREERA’ and the last occurrence of the word ‘of’ to be replaced by ‘123’.arrow_forwardWrite a java class method named addQuotes that takes one parameter of type String. The method should return a string that's indentical to it's argument, but with a double quote character added at the beginning and end of the string.arrow_forward
- In this problem you will fill out three functions to complete the Group ADT and the Diner ADT. The goal is to organize how diners manage the groups that want to eat there and the tables where these groups sit. It is important to take the time to read through the docstrings and the doctests. Additionally, make sure to not violate abstraction barriers for other ADTS, i.e. when implementing functions for the Diner ADT, do not violate abstraction barriers for the Group ADT, and vice versa. # Diner ADT def make_diner (name): """ Diners are represented by their name and the number of free tables they have.""" return [name, 0] def num_free_tables (diner): return diner [1] def name (diner): return diner [0] # You will implement add_table and serve which are part of the Diner ADT # Group ADT def make_group (name): Groups are represented by their name and their status.""" return [name, 'waiting'] |||||| def name (group): return group [0] def status (group): return group [1] def start_eating…arrow_forwardLab 6 - Exercise 2. Write a test driver that reads data about two surgeons and print the specialization of the doctor with the highest salary using the method that compares the salary of surgeons. A Doctor class has the following private data members, constructor, and public methods: name (String) salary (int) End of document I A constructor without parameters, A constructor with parameters, A set method for the data variables (one method) A get method for each data members. A method to print Doctor information A Surgeon is a subclass of Doctor with the following private data members, constructor, and public methods: specialization (String) degree (string) A constructor without parameters, A constructor with parameters, · A set method for the data variables (one method) · A get method for each data member. · A method to print all Surgeon information. · A method that compares the salary of two Surgeons and return the specialization of the doctor with the higher salary. 1. Implement the…arrow_forwardIn Java, please. Complete the Course class by implementing the findStudentHighestGpa() method, which returns the Student object with the highest GPA in the course. Assume that no two students have the same highest GPA. Given classes: Class LabProgram contains the main method for testing the program. Class Course represents a course, which contains an ArrayList of Student objects as a course roster. (Type your code in here.) Class Student represents a classroom student, which has three fields: first name, last name, and GPA. (Hint: getGPA() returns a student's GPA.) Note: For testing purposes, different student values will be used. Ex. For the following students: Henry Nguyen 3.5 Brenda Stern 2.0 Lynda Robison 3.2 Sonya King 3.9 the output is: Top student: Sonya King (GPA: 3.9) LabProgram.java import java.util.Scanner; public class LabProgram { public static void main(String args[]) { Scanner scnr = new Scanner(System.in); Course course = new Course(); int…arrow_forward
- Computer Programming Java Write a method named FirstHalf that receives a String parameter named word and then returns the first half of the string. You are guaranteed as a precondition that word has an even length greater than 1.arrow_forwardI have a Programming Question, The following is a class definition for a simple Ebook. So i need to write a second constructor that takes a String array of pages as input and sets the String array instance variable equal to the input. Continue to default the current page number to zero. Part 2: Write a getter and a setter method for the page number variable. The setter should check to make sure that the input is a valid page number and only update the variable if the new value is valid. Part 3: Write a getCurrentPage method that returns the String of the current page indexed by current_page. Here below are the two instance variables and one parameterless constructor that were provided public class Ebook{ private String[] pages; private int current_page; //constructor public Ebook() { this.pages = {"See Spot.", "See Spot run.", "Run, Spot, run."}; this.current_page = 0; }}arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education