SlideShare a Scribd company logo
1 of 24
Write a class called Fraction with the two instance variables
denominator and numerator. Include constructors, toString,
accessors, mutators, equals, also write the following methods:
Constructor with two arguments Simplify that simplifies a
given Fraction object, returns a Fraction Multiplication:
multiplies two fraction object, returns a Fraction Subtraction:
subtract two fraction objects, returns a Fraction Addition: adds
two fraction objects, returns a fraction Division: divides two
fraction objects, returns a fraction Reciprocal: finds the
reciprocal of a fraction, returns a fraction equals: returns a
Boolean toString: returns a string
Solution
import java.util.Scanner;
/****************************************************
******
Fraction.java - a Java representation of a fraction
Description: This class provides storage for internal
representation of, and methods to manipulate fractions.
A fraction consists of two integers, one for numerator
and one for denominator.
A valid fraction must not have zero in the denominator.
*****************************************************
******/
import java.lang.*;
import java.io.*;
import java.util.*;
public class Fraction
{
// member variables
private int numerator, denominator; // stores the fraction data
/****************************************************
******
Method: Default Constructor
Purpose: Create a new Fraction object and initialize it
with "invalid" data
Parameters: None
Preconditions: None
Postconditions: a new fraction object is created with numerator
and denominator set to 0
*****************************************************
******/
public Fraction()
{
numerator = denominator = 0;
}
public Fraction( int numerator, int denominator ) {
if (denominator == 0)
throw new NumberFormatException( "denominator is zero");
this.numerator = numerator;
this.denominator = denominator;
this.reduce();
}
/********************************************/
/* public accessor methods for private data */
/********************************************/
/****************************************************
******
Method: getNumerator
Purpose: access data stored in numerator member variable
Parameters: None
Preconditions: None
Postconditions: None
Returns: integer data stored in numerator member variable
*****************************************************
******/
public int getNumerator()
{
return numerator;
}
/****************************************************
******
Method: setNumerator
Purpose: provide data to store in numerator member variable
Parameters: num: an integer value
Preconditions: None
Postconditions: the value of num will be stored in numerator
member variable
*****************************************************
******/
public void setNumerator(int num)
{
numerator=num;
}
/****************************************************
******
Method: getDenominator
Purpose: access data stored in denominator member variable
Parameters: None
Preconditions: None
Postconditions: None
Returns: integer data stored in denominator member variable
*****************************************************
******/
public int getDenominator()
{
return denominator;
}
public boolean equals (Fraction fraction){
if ( this.numerator == fraction.numerator && this.denominator
== fraction.denominator)
return true;
else return false;
}
/****************************************************
******
Method: length
Purpose: Finds length of specified fraction.
Created by Stewart Bracken
*****************************************************
*****/
public int length(){
int count = 0; // at least 3 for num, denom, and /
boolean negative = false;
//if (this.numerator<0) negative = true;
String buffer = Integer.toString(this.numerator);
count +=buffer.length();
if (this.denominator != 1) {
buffer = Integer.toString(this.denominator);
count +=buffer.length();
count++; //acount for /
}
return count;
}
/****************************************************
******
Method: setDenominator
Purpose: provide data to store in denominator member variable
Parameters: den: an integer value
Preconditions: None
Postconditions: the value of den will be stored in denominator
member variable
*****************************************************
******/
public void setDenominator(int den)
{
denominator=den;
}
/****************************************************
/
/* public action methods for manipulating fractions */
/****************************************************
/
/*********************************************** *****
******
Method: add
Purpose: Add two fractions, a and b, where a is the "this"
object, and b is passed as the input parameter
Parameters: b, the fraction to add to "this"
Preconditions: Both fractions a and b must contain valid values
Postconditions: None
Returns: A Fraction representing the sum of two
fractions a & b
*****************************************************
******/
public Fraction add(Fraction b)
{
// check preconditions
if ((denominator == 0) || (b.denominator == 0))
throw new IllegalArgumentException( "invalid denominator");
// find lowest common denominator
int common = lcd(denominator, b.denominator);
// convert fractions to lcd
Fraction commonA = new Fraction();
Fraction commonB = new Fraction();
commonA = convert(common);
commonB = b.convert(common);
// create new fraction to return as sum
Fraction sum = new Fraction();
// calculate sum
sum.numerator = commonA.numerator + commonB.numerator;
sum.denominator = common;
// reduce the resulting fraction
sum = sum.reduce();
return sum;
}
/****************************************************
******
Method: subtract
Purpose: Subtract fraction b from a, where a is the "this"
object, and b is passed as the input parameter
Parameters: b, the fraction to subtract from "this"
Preconditions: Both fractions a and b must contain valid values
Postconditions: None
Returns: A Fraction representing the differenct of the
two fractions a & b
*****************************************************
******/
public Fraction subtract(Fraction b)
{
// check preconditions
if ((denominator == 0) || (b.denominator == 0))
throw new IllegalArgumentException( "invalid denominator");
// find lowest common denominator
int common = lcd(denominator, b.denominator);
// convert fractions to lcd
Fraction commonA = new Fraction();
Fraction commonB = new Fraction();
commonA = convert(common);
commonB = b.convert(common);
// create new fraction to return as difference
Fraction diff = new Fraction();
// calculate difference
diff.numerator = commonA.numerator - commonB.numerator;
diff.denominator = common;
// reduce the resulting fraction
diff = diff.reduce();
return diff;
}
/****************************************************
******
Method: multiply
Purpose: Multiply fractions a and b, where a is the "this"
object, and b is passed as the input parameter
Parameters: The fraction b to multiply "this" by
Preconditions: Both fractions a and b must contain valid values
Postconditions: None
Returns: A Fraction representing the product of the
two fractions a & b
*****************************************************
******/
public Fraction multiply(Fraction b)
{
// check preconditions
if ((denominator == 0) || (b.denominator == 0))
throw new IllegalArgumentException("invalid denominator");
// create new fraction to return as product
Fraction product = new Fraction();
// calculate product
product.numerator = numerator * b.numerator;
product.denominator = denominator * b.denominator;
// reduce the resulting fraction
product = product.reduce();
return product;
}
/****************************************************
******
Method: divide
Purpose: Divide fraction a by b, where a is the "this"
object, and b is passed as the input parameter
Parameters: The fraction b to divide "this" by
Preconditions: Both fractions a and b must contain valid values
Postconditions: None
Returns: A Fraction representing the result of dividing
fraction a by b
*****************************************************
******/
public Fraction divide(Fraction b)
{
// check preconditions
if ((denominator == 0) || (b.numerator == 0))
throw new IllegalArgumentException( "invalid denominator");
// create new fraction to return as result
Fraction result = new Fraction();
// calculate result
result.numerator = numerator * b.denominator;
result.denominator = denominator * b.numerator;
// reduce the resulting fraction
result = result.reduce();
return result;
}
public Fraction inverse(Fraction b){
if ((denominator == 0) || (b.numerator == 0))
throw new IllegalArgumentException( "invalid denominator");
Fraction result = new Fraction();
result.numerator = b.denominator;
result.denominator = b.numerator;
result = result.reduce();
return result;
//if ( result.numerator > && result.numerator < 0 )
}
/****************************************************
******
Method: input
Purpose: Retrieve values from the user via keyboard input
for numerator and denominator of the "this" object.
A valid integer value must be entered for the
numerator, and a non-zero integer value must be
entered for denominator.
Parameters: None
Preconditions: SavitchIn class must be available to read
keyboard
input. User needs to see command line window to be
prompted for input.
Postconditions: The "this" object will contain the valid data
entered
by the user.
*****************************************************
******/
public void input()
{
Scanner sc=new Scanner(System.in);
// prompt user to enter numerator
System.out.print("Please enter an integer for numerator: ");
// get user input
numerator = sc.nextInt();
// prompt user to enter denominator in a loop to prevent
// an invalid (zero) value for denominator
do {
System.out.print("Please enter a non-zero integer for
denominator: ");
denominator = sc.nextInt();
// make sure it is non-zero
if (denominator == 0)
System.out.println("Invalid value. Please try again.");
} while (denominator == 0);
}
/****************************************************
******
Method: output
Purpose: Print the value of the "this" object to the screen.
Makes use of the toString() method.
Uses System.out.print, rather than println for flexibility
Parameters: None
Preconditions: User needs access to command line window to
see output
Postconditions: The value of the "this" object will be printed
to
the screen
*****************************************************
******/
public void output()
{
//this.reduce();
System.out.print(this);
}
/******************************** ********************
******
Method: toString
Purpose: Convert the internal representation of a fraction,
which is stored in two integers, into a String
(which could then be printed to the screen)
Parameters: None
Preconditions: None
Postconditions: The value of the "this" object will be
converted
to a String
Returns: A String representation of the "this" fraction
*****************************************************
******/
public String toString()
{
String buffer;
if (denominator!=1) buffer = numerator + "/" + denominator;
else buffer = Integer.toString(numerator);
return buffer;
}
/****************************************************
*/
/* private methods used internally by Fraction class */
/****************************************************
*/
/****************************************************
******
Method: lcd
Purpose: find lowest common denominator, used to add and
subtract fractions
Parameters: two integers, denom1 and denom2
Preconditions: denom1 and denom2 must be non-zero integer
values
Postconditions: None
Returns: the lowest common denominator between denom1 and
denom2
*****************************************************
******/
private int lcd(int denom1, int denom2)
{
int factor = denom1;
while ((denom1 % denom2) != 0)
denom1 += factor;
return denom1;
}
/****************************************************
******
Method: gcd
Purpose: find greatest common denominator, used to reduce
fractions
Parameters: two integers, denom1 and denom2
Preconditions: denom1 and denom2 must be positive integer
values
denom1 is assumed to be greater than denom2
(denom1 > denom2 > 0)
Postconditions: None
Returns: the greatest common denominator between denom1
and
denom2
Credits: Thanks to Euclid for inventing the gcd algorithm,
and to Prof. Joyce for explaining it to me.
*****************************************************
******/
private int gcd(int denom1, int denom2)
{
int factor = denom2;
while (denom2 != 0) {
factor = denom2;
denom2 = denom1 % denom2;
denom1 = factor;
}
return denom1;
}
/****************************************************
******
Method: convert
Purpose: convert a fraction to an equivalent one based on
a lowest common denominator
Parameters: an integer common, the new denominator
Preconditions: the "this" fraction must contain valid data for
numerator and denominator
the integer value common is assumed to be greater
than the "this" fraction's denominator
Postconditions: None
Returns: A new fraction which is equivalent to the "this"
fraction, but has been converted to the new
denominator called common
*****************************************************
******/
private Fraction convert(int common)
{
Fraction result = new Fraction();
int factor = common / denominator;
result.numerator = numerator * factor;
result.denominator = common;
return result;
}
/****************************************************
******
Method: reduce
Purpose: convert the "this" fraction to an equivalent one
based on a greatest common denominator
Parameters: None
Preconditions: The "this" fraction must contain valid data for
numerator and denominator
Postconditions: None
Returns: A new fraction which is equivalent to a, but has
been reduced to its lowest numerical form
*****************************************************
******/
private Fraction reduce()
{
Fraction result = new Fraction();
int common = 0;
// get absolute values for numerator and denominator
int num = Math.abs(numerator);
int den = Math.abs(denominator) ;
// figure out which is less, numerator or denominator
if (num > den)
common = gcd(num, den);
else if (num < den)
common = gcd(den, num);
else // if both are the same, don't need to call gcd
common = num;
// set result based on common factor derived from gcd
result.numerator = numerator / common;
result.denominator = denominator / common;
if (result.numerator < 0 && result.denominator < 0){
result.numerator = -result.numerator;
result.denominator = -result.denominator;
} else if ( result.numerator >= 0 && result.denominator < 0){
result.denominator =-result.denominator;
result.numerator =-result.numerator;
}
return result;
}
/****************************************************
******
Method: main
Purpose: Show how to create some Fraction objects and then
call methods to manipulate them
Parameters: an array of Strings, expected to be empty
Preconditions: None
Postconditions: None
*****************************************************
******/
public static void main(String args[])
{
Fraction f1 = new Fraction(); // local fraction objects
Fraction f2 = new Fraction(); // used to test methods
// one way to set up fractions is simply to hard-code some
values
f1.setNumerator(1);
f1.setDenominator(3);
f2.setNumerator(1);
f2.setDenominator(6);
// try some arithmetic on these fractions
Fraction result = new Fraction();
// test addition
result = f1.add(f2);
// one way to output results, using toString method directly
System.out.println(f1 + " + " + f2 + " = " + result);
// test addition going the other way - should be same result
result = f2.add(f1);
// output results
System.out.println(f2 + " + " + f1 + " = " + result);
System.out.println();
// test subtraction
result = f1.subtract(f2);
// output results
System.out.println(f1 + " - " + f2 + " = " + result);
// test subtraction going the other way - should be different
result
result = f2.subtract(f1);
// output results
System.out.println(f2 + " - " + f1 + " = " + result);
// another way to set up fractions is to get user input
System.out.println();
System.out.println("Fraction 1:");
f1.input();
System.out.println();
System.out.println("Fraction 2:");
f2.input();
System.out.println();
// test multiplication
result = f1.multiply(f2);
// // another way to output results is to use the output method
// // this uses the toString method indirectly
f1.output();
System.out.print(" * ");
f2.output();
System.out.print(" = ");
result.output();
System.out.println();
// test division
result = f1.divide(f2);
// output results
f1.output();
System.out.print(" / ");
f2.output();
System.out.print(" = ");
result.output();
System.out.println();
}
}

More Related Content

Similar to Write a class called Fraction with the two instance variables denomin.docx

For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
budbarber38650
 
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdfg++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
arakalamkah11
 
can someone fix the errors in this code- the name needs to be Fraction.pdf
can someone fix the errors in this code- the name needs to be Fraction.pdfcan someone fix the errors in this code- the name needs to be Fraction.pdf
can someone fix the errors in this code- the name needs to be Fraction.pdf
vinaythemodel
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
jyothimuppasani1
 
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfC++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
rohit219406
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdf
deepaarora22
 
Pro.docx
Pro.docxPro.docx
import java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdf
import java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdfimport java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdf
import java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdf
aquacareser
 
Java programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdfJava programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdf
fathimafancy
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
Vince Vo
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
eyebolloptics
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
fashiongallery1
 
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docxstudent start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
hanneloremccaffery
 
I have the first program completed (not how request, but it works) a.pdf
I have the first program completed (not how request, but it works) a.pdfI have the first program completed (not how request, but it works) a.pdf
I have the first program completed (not how request, but it works) a.pdf
footworld1
 
C# Programming. Using methods to call results to display. The code i.pdf
C# Programming. Using methods to call results to display. The code i.pdfC# Programming. Using methods to call results to display. The code i.pdf
C# Programming. Using methods to call results to display. The code i.pdf
fatoryoutlets
 
META-INFMANIFEST.MFManifest-Version 1.0Created-By 1.8.0_.docx
META-INFMANIFEST.MFManifest-Version 1.0Created-By 1.8.0_.docxMETA-INFMANIFEST.MFManifest-Version 1.0Created-By 1.8.0_.docx
META-INFMANIFEST.MFManifest-Version 1.0Created-By 1.8.0_.docx
houndsomeminda
 

Similar to Write a class called Fraction with the two instance variables denomin.docx (20)

Modify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutletModify the bouncing ball example demonstrated/tutorialoutlet
Modify the bouncing ball example demonstrated/tutorialoutlet
 
For this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docxFor this project, write a program that stores integers in a binary.docx
For this project, write a program that stores integers in a binary.docx
 
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdfg++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
g++ -o simpleVector.exe simpleVector.cpp #include stdio.h #i.pdf
 
can someone fix the errors in this code- the name needs to be Fraction.pdf
can someone fix the errors in this code- the name needs to be Fraction.pdfcan someone fix the errors in this code- the name needs to be Fraction.pdf
can someone fix the errors in this code- the name needs to be Fraction.pdf
 
write the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdfwrite the To Dos to get the exact outputNOte A valid Fraction .pdf
write the To Dos to get the exact outputNOte A valid Fraction .pdf
 
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdfC++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
C++, Implement the class BinarySearchTree, as given in listing 16-4 .pdf
 
Memory Management In C++
Memory Management In C++Memory Management In C++
Memory Management In C++
 
Ive posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdfIve posted 3 classes after the instruction that were given at star.pdf
Ive posted 3 classes after the instruction that were given at star.pdf
 
Pro.docx
Pro.docxPro.docx
Pro.docx
 
import java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdf
import java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdfimport java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdf
import java.util.Random;ASSIGNMENT #2 MATRIX ARITHMETIC Cla.pdf
 
Java programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdfJava programI made this Account.java below. Using the attached cod.pdf
Java programI made this Account.java below. Using the attached cod.pdf
 
Java căn bản - Chapter7
Java căn bản - Chapter7Java căn bản - Chapter7
Java căn bản - Chapter7
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Write a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdfWrite a program that mimics the operations of several vending machin.pdf
Write a program that mimics the operations of several vending machin.pdf
 
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdfUsing c++Im also using a the ide editor called CodeLiteThe hea.pdf
Using c++Im also using a the ide editor called CodeLiteThe hea.pdf
 
Ch10 Program Organization
Ch10 Program OrganizationCh10 Program Organization
Ch10 Program Organization
 
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docxstudent start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
student start_code_U08223_cwk1 (1).DS_Store__MACOSXstudent.docx
 
I have the first program completed (not how request, but it works) a.pdf
I have the first program completed (not how request, but it works) a.pdfI have the first program completed (not how request, but it works) a.pdf
I have the first program completed (not how request, but it works) a.pdf
 
C# Programming. Using methods to call results to display. The code i.pdf
C# Programming. Using methods to call results to display. The code i.pdfC# Programming. Using methods to call results to display. The code i.pdf
C# Programming. Using methods to call results to display. The code i.pdf
 
META-INFMANIFEST.MFManifest-Version 1.0Created-By 1.8.0_.docx
META-INFMANIFEST.MFManifest-Version 1.0Created-By 1.8.0_.docxMETA-INFMANIFEST.MFManifest-Version 1.0Created-By 1.8.0_.docx
META-INFMANIFEST.MFManifest-Version 1.0Created-By 1.8.0_.docx
 

More from ajoy21

Please choose one of the following questions to answer for this week.docx
Please choose one of the following questions to answer for this week.docxPlease choose one of the following questions to answer for this week.docx
Please choose one of the following questions to answer for this week.docx
ajoy21
 
Please answer to this discussion post. No less than 150 words. Refer.docx
Please answer to this discussion post. No less than 150 words. Refer.docxPlease answer to this discussion post. No less than 150 words. Refer.docx
Please answer to this discussion post. No less than 150 words. Refer.docx
ajoy21
 
Please answer the question .There is no work count. PLEASE NUMBER .docx
Please answer the question .There is no work count. PLEASE NUMBER .docxPlease answer the question .There is no work count. PLEASE NUMBER .docx
Please answer the question .There is no work count. PLEASE NUMBER .docx
ajoy21
 
Please answer the three questions completly. I have attached the que.docx
Please answer the three questions completly. I have attached the que.docxPlease answer the three questions completly. I have attached the que.docx
Please answer the three questions completly. I have attached the que.docx
ajoy21
 

More from ajoy21 (20)

Please complete the assignment listed below.Define and explain, us.docx
Please complete the assignment listed below.Define and explain, us.docxPlease complete the assignment listed below.Define and explain, us.docx
Please complete the assignment listed below.Define and explain, us.docx
 
Please cite sources for each question. Do not use the same sources f.docx
Please cite sources for each question. Do not use the same sources f.docxPlease cite sources for each question. Do not use the same sources f.docx
Please cite sources for each question. Do not use the same sources f.docx
 
Please choose one of the following questions to answer for this week.docx
Please choose one of the following questions to answer for this week.docxPlease choose one of the following questions to answer for this week.docx
Please choose one of the following questions to answer for this week.docx
 
Please check the attachment for my paper.Please add citations to a.docx
Please check the attachment for my paper.Please add citations to a.docxPlease check the attachment for my paper.Please add citations to a.docx
Please check the attachment for my paper.Please add citations to a.docx
 
Please answer to this discussion post. No less than 150 words. Refer.docx
Please answer to this discussion post. No less than 150 words. Refer.docxPlease answer to this discussion post. No less than 150 words. Refer.docx
Please answer to this discussion post. No less than 150 words. Refer.docx
 
Please attach Non-nursing theorist summaries.JigsawExecutive .docx
Please attach Non-nursing theorist summaries.JigsawExecutive .docxPlease attach Non-nursing theorist summaries.JigsawExecutive .docx
Please attach Non-nursing theorist summaries.JigsawExecutive .docx
 
Please answer the question .There is no work count. PLEASE NUMBER .docx
Please answer the question .There is no work count. PLEASE NUMBER .docxPlease answer the question .There is no work count. PLEASE NUMBER .docx
Please answer the question .There is no work count. PLEASE NUMBER .docx
 
Please answer the following questions. Please cite your references..docx
Please answer the following questions. Please cite your references..docxPlease answer the following questions. Please cite your references..docx
Please answer the following questions. Please cite your references..docx
 
Please answer the following questions.1.      1.  Are you or.docx
Please answer the following questions.1.      1.  Are you or.docxPlease answer the following questions.1.      1.  Are you or.docx
Please answer the following questions.1.      1.  Are you or.docx
 
Please answer the following question with 200-300 words.Q. Discu.docx
Please answer the following question with 200-300 words.Q. Discu.docxPlease answer the following question with 200-300 words.Q. Discu.docx
Please answer the following question with 200-300 words.Q. Discu.docx
 
Please answer the following question Why do you think the US ha.docx
Please answer the following question Why do you think the US ha.docxPlease answer the following question Why do you think the US ha.docx
Please answer the following question Why do you think the US ha.docx
 
Please answer the following questions. Define tunneling in the V.docx
Please answer the following questions. Define tunneling in the V.docxPlease answer the following questions. Define tunneling in the V.docx
Please answer the following questions. Define tunneling in the V.docx
 
Please answer the following questions1. How can you stimulate the.docx
Please answer the following questions1. How can you stimulate the.docxPlease answer the following questions1. How can you stimulate the.docx
Please answer the following questions1. How can you stimulate the.docx
 
Please answer the following questions very deeply and presicely .docx
Please answer the following questions very deeply and presicely .docxPlease answer the following questions very deeply and presicely .docx
Please answer the following questions very deeply and presicely .docx
 
Please answer the following questions in an informal 1 ½ - 2-page es.docx
Please answer the following questions in an informal 1 ½ - 2-page es.docxPlease answer the following questions in an informal 1 ½ - 2-page es.docx
Please answer the following questions in an informal 1 ½ - 2-page es.docx
 
Please answer the following questions in a response of 150 to 200 wo.docx
Please answer the following questions in a response of 150 to 200 wo.docxPlease answer the following questions in a response of 150 to 200 wo.docx
Please answer the following questions in a response of 150 to 200 wo.docx
 
Please answer these questions regarding the (TILA) Truth in Lending .docx
Please answer these questions regarding the (TILA) Truth in Lending .docxPlease answer these questions regarding the (TILA) Truth in Lending .docx
Please answer these questions regarding the (TILA) Truth in Lending .docx
 
Please answer the following question pertaining to psychology. Inc.docx
Please answer the following question pertaining to psychology. Inc.docxPlease answer the following question pertaining to psychology. Inc.docx
Please answer the following question pertaining to psychology. Inc.docx
 
Please answer the following questions in a response of 250 to 300 .docx
Please answer the following questions in a response of 250 to 300 .docxPlease answer the following questions in a response of 250 to 300 .docx
Please answer the following questions in a response of 250 to 300 .docx
 
Please answer the three questions completly. I have attached the que.docx
Please answer the three questions completly. I have attached the que.docxPlease answer the three questions completly. I have attached the que.docx
Please answer the three questions completly. I have attached the que.docx
 

Recently uploaded

Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Recently uploaded (20)

UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Third Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptxThird Battle of Panipat detailed notes.pptx
Third Battle of Panipat detailed notes.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 

Write a class called Fraction with the two instance variables denomin.docx

  • 1. Write a class called Fraction with the two instance variables denominator and numerator. Include constructors, toString, accessors, mutators, equals, also write the following methods: Constructor with two arguments Simplify that simplifies a given Fraction object, returns a Fraction Multiplication: multiplies two fraction object, returns a Fraction Subtraction: subtract two fraction objects, returns a Fraction Addition: adds two fraction objects, returns a fraction Division: divides two fraction objects, returns a fraction Reciprocal: finds the reciprocal of a fraction, returns a fraction equals: returns a Boolean toString: returns a string Solution import java.util.Scanner; /**************************************************** ****** Fraction.java - a Java representation of a fraction Description: This class provides storage for internal representation of, and methods to manipulate fractions. A fraction consists of two integers, one for numerator and one for denominator. A valid fraction must not have zero in the denominator. ***************************************************** ******/
  • 2. import java.lang.*; import java.io.*; import java.util.*; public class Fraction { // member variables private int numerator, denominator; // stores the fraction data /**************************************************** ****** Method: Default Constructor Purpose: Create a new Fraction object and initialize it with "invalid" data Parameters: None Preconditions: None Postconditions: a new fraction object is created with numerator and denominator set to 0 ***************************************************** ******/ public Fraction() { numerator = denominator = 0; }
  • 3. public Fraction( int numerator, int denominator ) { if (denominator == 0) throw new NumberFormatException( "denominator is zero"); this.numerator = numerator; this.denominator = denominator; this.reduce(); } /********************************************/ /* public accessor methods for private data */ /********************************************/ /**************************************************** ****** Method: getNumerator Purpose: access data stored in numerator member variable Parameters: None Preconditions: None Postconditions: None Returns: integer data stored in numerator member variable ***************************************************** ******/ public int getNumerator() { return numerator;
  • 4. } /**************************************************** ****** Method: setNumerator Purpose: provide data to store in numerator member variable Parameters: num: an integer value Preconditions: None Postconditions: the value of num will be stored in numerator member variable ***************************************************** ******/ public void setNumerator(int num) { numerator=num; } /**************************************************** ****** Method: getDenominator Purpose: access data stored in denominator member variable Parameters: None Preconditions: None Postconditions: None
  • 5. Returns: integer data stored in denominator member variable ***************************************************** ******/ public int getDenominator() { return denominator; } public boolean equals (Fraction fraction){ if ( this.numerator == fraction.numerator && this.denominator == fraction.denominator) return true; else return false; } /**************************************************** ****** Method: length Purpose: Finds length of specified fraction. Created by Stewart Bracken *****************************************************
  • 6. *****/ public int length(){ int count = 0; // at least 3 for num, denom, and / boolean negative = false; //if (this.numerator<0) negative = true; String buffer = Integer.toString(this.numerator); count +=buffer.length(); if (this.denominator != 1) { buffer = Integer.toString(this.denominator); count +=buffer.length(); count++; //acount for / } return count; } /**************************************************** ****** Method: setDenominator Purpose: provide data to store in denominator member variable Parameters: den: an integer value Preconditions: None Postconditions: the value of den will be stored in denominator member variable *****************************************************
  • 7. ******/ public void setDenominator(int den) { denominator=den; } /**************************************************** / /* public action methods for manipulating fractions */ /**************************************************** / /*********************************************** ***** ****** Method: add Purpose: Add two fractions, a and b, where a is the "this" object, and b is passed as the input parameter Parameters: b, the fraction to add to "this" Preconditions: Both fractions a and b must contain valid values Postconditions: None Returns: A Fraction representing the sum of two fractions a & b ***************************************************** ******/
  • 8. public Fraction add(Fraction b) { // check preconditions if ((denominator == 0) || (b.denominator == 0)) throw new IllegalArgumentException( "invalid denominator"); // find lowest common denominator int common = lcd(denominator, b.denominator); // convert fractions to lcd Fraction commonA = new Fraction(); Fraction commonB = new Fraction(); commonA = convert(common); commonB = b.convert(common); // create new fraction to return as sum Fraction sum = new Fraction(); // calculate sum sum.numerator = commonA.numerator + commonB.numerator; sum.denominator = common; // reduce the resulting fraction sum = sum.reduce(); return sum; } /**************************************************** ****** Method: subtract
  • 9. Purpose: Subtract fraction b from a, where a is the "this" object, and b is passed as the input parameter Parameters: b, the fraction to subtract from "this" Preconditions: Both fractions a and b must contain valid values Postconditions: None Returns: A Fraction representing the differenct of the two fractions a & b ***************************************************** ******/ public Fraction subtract(Fraction b) { // check preconditions if ((denominator == 0) || (b.denominator == 0)) throw new IllegalArgumentException( "invalid denominator"); // find lowest common denominator int common = lcd(denominator, b.denominator); // convert fractions to lcd Fraction commonA = new Fraction(); Fraction commonB = new Fraction(); commonA = convert(common); commonB = b.convert(common); // create new fraction to return as difference Fraction diff = new Fraction(); // calculate difference
  • 10. diff.numerator = commonA.numerator - commonB.numerator; diff.denominator = common; // reduce the resulting fraction diff = diff.reduce(); return diff; } /**************************************************** ****** Method: multiply Purpose: Multiply fractions a and b, where a is the "this" object, and b is passed as the input parameter Parameters: The fraction b to multiply "this" by Preconditions: Both fractions a and b must contain valid values Postconditions: None Returns: A Fraction representing the product of the two fractions a & b ***************************************************** ******/ public Fraction multiply(Fraction b) { // check preconditions if ((denominator == 0) || (b.denominator == 0)) throw new IllegalArgumentException("invalid denominator");
  • 11. // create new fraction to return as product Fraction product = new Fraction(); // calculate product product.numerator = numerator * b.numerator; product.denominator = denominator * b.denominator; // reduce the resulting fraction product = product.reduce(); return product; } /**************************************************** ****** Method: divide Purpose: Divide fraction a by b, where a is the "this" object, and b is passed as the input parameter Parameters: The fraction b to divide "this" by Preconditions: Both fractions a and b must contain valid values Postconditions: None Returns: A Fraction representing the result of dividing fraction a by b ***************************************************** ******/ public Fraction divide(Fraction b) {
  • 12. // check preconditions if ((denominator == 0) || (b.numerator == 0)) throw new IllegalArgumentException( "invalid denominator"); // create new fraction to return as result Fraction result = new Fraction(); // calculate result result.numerator = numerator * b.denominator; result.denominator = denominator * b.numerator; // reduce the resulting fraction result = result.reduce(); return result; } public Fraction inverse(Fraction b){ if ((denominator == 0) || (b.numerator == 0)) throw new IllegalArgumentException( "invalid denominator"); Fraction result = new Fraction(); result.numerator = b.denominator; result.denominator = b.numerator; result = result.reduce(); return result; //if ( result.numerator > && result.numerator < 0 ) }
  • 13. /**************************************************** ****** Method: input Purpose: Retrieve values from the user via keyboard input for numerator and denominator of the "this" object. A valid integer value must be entered for the numerator, and a non-zero integer value must be entered for denominator. Parameters: None Preconditions: SavitchIn class must be available to read keyboard input. User needs to see command line window to be prompted for input. Postconditions: The "this" object will contain the valid data entered by the user. ***************************************************** ******/ public void input() { Scanner sc=new Scanner(System.in);
  • 14. // prompt user to enter numerator System.out.print("Please enter an integer for numerator: "); // get user input numerator = sc.nextInt(); // prompt user to enter denominator in a loop to prevent // an invalid (zero) value for denominator do { System.out.print("Please enter a non-zero integer for denominator: "); denominator = sc.nextInt(); // make sure it is non-zero if (denominator == 0) System.out.println("Invalid value. Please try again."); } while (denominator == 0); } /**************************************************** ****** Method: output Purpose: Print the value of the "this" object to the screen. Makes use of the toString() method. Uses System.out.print, rather than println for flexibility Parameters: None Preconditions: User needs access to command line window to see output
  • 15. Postconditions: The value of the "this" object will be printed to the screen ***************************************************** ******/ public void output() { //this.reduce(); System.out.print(this); } /******************************** ******************** ****** Method: toString Purpose: Convert the internal representation of a fraction, which is stored in two integers, into a String (which could then be printed to the screen) Parameters: None Preconditions: None Postconditions: The value of the "this" object will be converted to a String Returns: A String representation of the "this" fraction
  • 16. ***************************************************** ******/ public String toString() { String buffer; if (denominator!=1) buffer = numerator + "/" + denominator; else buffer = Integer.toString(numerator); return buffer; } /**************************************************** */ /* private methods used internally by Fraction class */ /**************************************************** */ /**************************************************** ****** Method: lcd Purpose: find lowest common denominator, used to add and subtract fractions Parameters: two integers, denom1 and denom2 Preconditions: denom1 and denom2 must be non-zero integer values Postconditions: None
  • 17. Returns: the lowest common denominator between denom1 and denom2 ***************************************************** ******/ private int lcd(int denom1, int denom2) { int factor = denom1; while ((denom1 % denom2) != 0) denom1 += factor; return denom1; } /**************************************************** ****** Method: gcd Purpose: find greatest common denominator, used to reduce fractions Parameters: two integers, denom1 and denom2 Preconditions: denom1 and denom2 must be positive integer values denom1 is assumed to be greater than denom2 (denom1 > denom2 > 0) Postconditions: None Returns: the greatest common denominator between denom1
  • 18. and denom2 Credits: Thanks to Euclid for inventing the gcd algorithm, and to Prof. Joyce for explaining it to me. ***************************************************** ******/ private int gcd(int denom1, int denom2) { int factor = denom2; while (denom2 != 0) { factor = denom2; denom2 = denom1 % denom2; denom1 = factor; } return denom1; } /**************************************************** ****** Method: convert Purpose: convert a fraction to an equivalent one based on a lowest common denominator Parameters: an integer common, the new denominator Preconditions: the "this" fraction must contain valid data for
  • 19. numerator and denominator the integer value common is assumed to be greater than the "this" fraction's denominator Postconditions: None Returns: A new fraction which is equivalent to the "this" fraction, but has been converted to the new denominator called common ***************************************************** ******/ private Fraction convert(int common) { Fraction result = new Fraction(); int factor = common / denominator; result.numerator = numerator * factor; result.denominator = common; return result; } /**************************************************** ****** Method: reduce Purpose: convert the "this" fraction to an equivalent one based on a greatest common denominator Parameters: None
  • 20. Preconditions: The "this" fraction must contain valid data for numerator and denominator Postconditions: None Returns: A new fraction which is equivalent to a, but has been reduced to its lowest numerical form ***************************************************** ******/ private Fraction reduce() { Fraction result = new Fraction(); int common = 0; // get absolute values for numerator and denominator int num = Math.abs(numerator); int den = Math.abs(denominator) ; // figure out which is less, numerator or denominator if (num > den) common = gcd(num, den); else if (num < den) common = gcd(den, num); else // if both are the same, don't need to call gcd common = num; // set result based on common factor derived from gcd result.numerator = numerator / common; result.denominator = denominator / common;
  • 21. if (result.numerator < 0 && result.denominator < 0){ result.numerator = -result.numerator; result.denominator = -result.denominator; } else if ( result.numerator >= 0 && result.denominator < 0){ result.denominator =-result.denominator; result.numerator =-result.numerator; } return result; } /**************************************************** ****** Method: main Purpose: Show how to create some Fraction objects and then call methods to manipulate them Parameters: an array of Strings, expected to be empty Preconditions: None Postconditions: None ***************************************************** ******/ public static void main(String args[]) { Fraction f1 = new Fraction(); // local fraction objects Fraction f2 = new Fraction(); // used to test methods
  • 22. // one way to set up fractions is simply to hard-code some values f1.setNumerator(1); f1.setDenominator(3); f2.setNumerator(1); f2.setDenominator(6); // try some arithmetic on these fractions Fraction result = new Fraction(); // test addition result = f1.add(f2); // one way to output results, using toString method directly System.out.println(f1 + " + " + f2 + " = " + result); // test addition going the other way - should be same result result = f2.add(f1); // output results System.out.println(f2 + " + " + f1 + " = " + result); System.out.println(); // test subtraction result = f1.subtract(f2); // output results System.out.println(f1 + " - " + f2 + " = " + result); // test subtraction going the other way - should be different
  • 23. result result = f2.subtract(f1); // output results System.out.println(f2 + " - " + f1 + " = " + result); // another way to set up fractions is to get user input System.out.println(); System.out.println("Fraction 1:"); f1.input(); System.out.println(); System.out.println("Fraction 2:"); f2.input(); System.out.println(); // test multiplication result = f1.multiply(f2); // // another way to output results is to use the output method // // this uses the toString method indirectly f1.output(); System.out.print(" * "); f2.output(); System.out.print(" = "); result.output(); System.out.println();
  • 24. // test division result = f1.divide(f2); // output results f1.output(); System.out.print(" / "); f2.output(); System.out.print(" = "); result.output(); System.out.println(); } }