Concept explainers
Modify the below program and add another public method called isEqual(). This method will determine if two fractions represent the same number (i.e. fraction), and return a Boolean result to indicate this. The method will take a Fraction class object as a parameter to compare with the ‘calling object’. We need to find a way to equate fractions represented as two integers. Modify your client class to test the Fraction class functionality that has been just added.
import java.util.ArrayList;
import java.util.Scanner;
//Define the class Fraction
class Fraction
{
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);
}
//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());
}
}
//Define the class TestFraction
class Main
{
//Define the main method
public static void main(String[] args)
{
//Declare the variables to store the numerator and denominator
String res;
int num, den;
//Declare an ArrayList to store the results
ArrayList<Fraction> fractions = new ArrayList<>();
//Create the object for scanner class
Scanner sc = new Scanner(System.in);
//use the do-while loop to iterate test the conditions
do
{
//Prompts the user to enter the numerator
System.out.print("Enter the num: ");
//Store the Integer part only
num = Integer.parseInt(sc.nextLine().trim());
//If the numerator is less than zero
if(num < 0)
//Break from loop
break;
//Prompts the user to enter the denominator
System.out.print("Enter the den: ");
//store the integer part only
den = Integer.parseInt(sc.nextLine().trim());
//Create the object of Fraction class
Fraction fraction = new Fraction(num, den);
//Add the resultant fractions into the ArrayList
fractions.add(fraction);
res = fraction.getSimplifiedFraction();
System.out.println("\tFraction added to list as: " + res + "\n"); //Display the resultant fraction
}while(res != "0");
//Display all fractions that are stored in the ArrayList
System.out.println("\nDISPLAYING ALL FRACTIONS:\n"
+ "-------------------------");
//Use the loop to display the values stored in the ArrayList
for(Fraction fr : fractions)
fr.display();
//to print the new line
System.out.println();
}
}
Step by stepSolved in 4 steps with 7 images
- Add a private method simplify() to your Fraction class that converts a fraction to its simplest form. For example, the fraction 20 / 60 should be stored in the class instance variables as 1 / 3 (i.e. numerator = 1, denominator = 3). N.B.you will need a method to determine the Greatest Common Divisor (GCD.both of these methods (simplify and gcd) must be private. Asthese methods are private, client programs cannot access them. They can only be accessed within the Fraction class. Given their purpose, it would mean that any Fraction class method that modifies theinstance variables (e.g.: input, add, constructor, set) should call the simplify() method to reduce the instance variables to their minimum values. import java.util.ArrayList;import java.util.Scanner; class Fraction{private int n, d;public Fraction(){this.n = this.d = 0;}public Fraction(int n, int d){this.n = n;this.d = d;} public int getNum(){return n;}public int getDen(){return d;}public boolean isZero(){return(getNum() == 0…arrow_forwardWrite 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_forwardWrite a method for the farmer class that allows a farmer object to pet all cows on the farm. Do not use arrays.arrow_forward
- For this lab task, you will work with classes and objects. Create a class named text that works similar to the built-in string class. You will need to define a constructor that can be used to initialize objects of this new class with some literal text. Next, define three methods: to_upper() that will convert all characters to uppercase, reverse() that will reverse the text and length() that will return the length of the text. After you have completed this part, copy the following mainfunction to your code and check if the implementation is correct. int main() { text sample = "This is a sample text"; cout << sample.to_upper(); // This should display "THIS IS A SAMPLE TEXT" cout << endl;cout << sample.reverse(); // This should display "txet elpmas a si sihT"cout << endl; cout << sample.length(); // This should display 21 }arrow_forwardRequirement: In this assignment, you are going to handle exceptional cases in the bank account class for foreign currencies. In the attached files, source codes for ForeignCurrencyAccount and Account classes are given. There is also Test3.java and Transaction.java that run operations on the bank accounts. Please complete the implementation of ForeignCurrencyAccount and Account classes, so that following exceptional cases are handled by them. Do not add new attributes or methods to ForeignCurrencyAccount and Account classes. Just add code to throw exceptions or handle exceptions. Exceptional cases: 1. Whenever a transaction amount given to "withdraw" method is greater than account's balance, an exception of class InsufficientFundsException should be thrown. 2. Whenever InsufficientFundsException is caught within buyForeignCurrency or sellForeignCurrency methods, an Exception should be thrown with description "Foreign currency buy/sell transaction failed because of insufficient funds".…arrow_forwardI don't know how to complete this. Modify the class named Billing that includes three overloaded computeBill() methods for a photo book store. • When computeBill() receives a single parameter, it represents the price of one photo book ordered. Add 8% tax, and return the total due. • When computeBill() receives two parameters, they represent the price of a photo book and the quantity ordered. Multiply the two values, add 8% tax, and return the total due. • When computeBill() receives three parameters, they represent the price of a photo book, the quantity ordered, and a coupon value. Multiply the quantity and price, reduce the result by the coupon value, and then add 8% tax and return the total due. public class Billing {final static double TAX = 0.08;public static void main(String[] args) {final double HIGHPRICE = 24.99;final double MEDPRICE = 17.50;final double LOPRICE = 10.00;final int QUAN1 = 4;final int QUAN2 = 6;double bill;bill = computeBill(HIGHPRICE);System.out.println("The…arrow_forward
- Add another public method dblValue() to your Fraction class which returns the double precision approximation value of the fraction. That is, the floating point result of actually dividing numerator by denominator. N.B. this method does not do any display itself, but can be called by a client program to be used in an output statement. Eg: if a client has a fraction frac that represents 1 / 2, then a method call to frac.dblValue() should return the double number 0.5. Use your client program to test this functionality; i.e. provide an output statement to display the double value of a fractionhere are my codes /** To change this license header, choose License Headers in Project Properties.* To change this template file, choose Tools | Templates* and open the template in the editor.*/package lab4; /**** @author engko*/public class Fraction {//Define the class Fraction// declaring instance variablesString res;private int num, denom; // default constructor to initialize instance…arrow_forwardI am getting an error: findOrCreate()Cannot resolve method findOrCreate in RolePermission.Also, when I try Option 3: The method cannot be reference if it is non-static. I'm not too familiar with it so do you suggest I make it static?arrow_forwardModify the program below and add a public method called isZero() to the Fraction class. This method will determine if a Fraction represents a zero fraction. A zero fraction has a numerator == 0, no matter what the denominator is. Your isZero() method should return a Boolean resultindicating a zero fraction or otherwise. The method will be used by the client class to test whether the ‘calling fraction’ is equal to the number zero. Modify the program so that it now loops until a fraction representing zero is entered. //Import the essential package import java.util.ArrayList; import java.util.Scanner; //Define the class Fraction class Fraction { private int n, d; public Fraction() { //Initialize the values this.n = this.d = 0; } public Fraction(int n, int d) { //Initialize the variables this.n = n; this.d = d; } //Define the getter function getNum() that returns the numerator public int getNum() {…arrow_forward
- Design a class called "Person" with attributes for name, age, and gender. Implement methods to get and set these attributes, and also a method to calculate the person's age in dog years (assuming 1 dog year is equivalent to 7 human years).arrow_forwardCan I get a help with this in Java please? Introduce a new class, called Borrower to the project. Its purpose is to represent the borrower of the CD. It should have two fields surname and libraryId; where the latter is a mix of letters and numbers, and a suitable constructor with parameters for only these two fields in the order specified above as well as appropriate accessor methods.arrow_forwardWrite a main method, in which you should have an Arralylist of students, in which you should include every student. You should have a PhD student named Joe Smith. In addition, you should create an Undergraduate student object for each of your team members (setting their names). If you’re only one person doing the assignment, then you should just create one undergraduate object. For each undergraduate student, you should add add two courses (COIS 2240 and COIS 1020). Loop over the arraylist of students, print their names, if the student is an undergraduate student, print their courses.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