SlideShare a Scribd company logo
1 of 8
Download to read offline
PROGRAM 2 – Fraction Class
Problem For this programming assignment, you are to implement the Fraction class design
given below (and discussed in class). You are also to develop an appropriate test driver that
thoroughly tests the class.
Fraction Class Design Implement the following class design. Make sure to use implement the
methods to have the same names as given below, with the same number and types of parameters.
public class Fraction {
private int numer;
private int denom;
// alternate constructor
public Fraction(int numer, int denom)
throws InvalidDenominatorException {
}
// copy constructor
public Fraction(Fraction otherFrac) {
}
// getters
public int getNumer() {
}
public int getDenom() {
}
// standard methods
public String toString() {
}
public boolean equals(Fraction rFrac) {
}
// fraction operators
public Fraction add(Fraction rFrac) {
}
public Fraction sub(Fraction rFrac) {
}
public Fraction mult(Fraction rFrac) {
}
public Fraction div(Fraction rFrac) {
}
public boolean isSimplestForm() {
}
public Fraction reduce() {
}
public boolean properFrac() {
}
public Fraction abs() {
}
public boolean lessThan(Fraction rFrac) {
}
public boolean greaterThan(Fraction rFrac) {
}
public double convertToDecimal() {
}
public Fraction invert() {
}
}
Note that objects of type Fraction are immutable. Also, the alternate constructor throws an
InvalidDenominatorException if passed a denominator value of 0. This exception type is not
predefined in Java, so you must define it as follow as another class in your Java project files:
public class InvalidDenominatorException extends RuntimeException { } // nothing to
implement
This creates an exception of type RuntimeException. RuntimeExceptions do not need to be
caught when thrown. However, your test driver should have the code for catching this exception
where appropriate.
For example, if your test driver excutes the following,
Fraction frac1 = new Fraction(1,2);
then there is no need to catch the possible exception, since it is clear that the denominator is not
0. However, if the value are input by the user, then there is a chance that a denominator vaue of 0
could be entered, and therefore the code for catching the possible exception is needed,
int numer, denom;
Fraction frac1;
Scanner input = new Scanner(System.in);
Boolean valid_input = false;
while (!valid_input) try {
System.out.print(“Enter numerator denominator: “);
numer = input.nextInt();
denom = input.nextInt();
frac1 = new Fraction(numer,denom);
valid_input = true;
}
catch (InvalidDenominatorException e) {
System.out.println(“Denominator of Zero found – Please reenter”);
}
catch (InputMismatchException e) {
System.out.println(“Non-digit character found – Please reenter”);
} etc.
Considerations
Makes sure the equals method returns true for any two fractions that are arithmetically equal.
Make sure that the equals, lessThan and greaterThan methods do not alter the values of the
fractions being compared. You may consider the use of private methods that are called by the
public methods of the class, but not accessible to the users (“client code”).
Solution
Hi, Please find my implementation.
Please let me know in case of any issue.
public class Fraction {
private int numer;
private int denom;
// alternate constructor
public Fraction(int numer, int denom) throws InvalidDenominatorException{
if(denom == 0)
throw new InvalidDenominatorException();
this.numer = numer;
this.denom = denom;
}
// copy constructor
public Fraction(Fraction otherFrac) {
numer = otherFrac.numer;
denom = otherFrac.denom;
}
// getters
public int getNumer() {
return numer;
}
public int getDenom() {
return denom;
}
// standard methods
public String toString() {
int n = numer;
int d = denom;
if(d < 0){
n = -n; // converting n as negative
d = -d; // converting d as positive
}
if(d == 1)
return Integer.toString(n);
return n + "/" + d;
}
public boolean equals(Fraction rFrac) {
return convertToDecimal() == rFrac.convertToDecimal();
}
// fraction operators
public Fraction add(Fraction rFrac) {
int a = this.numer;
int b = this.denom;
int c = rFrac.numer;
int d = rFrac.denom;
Fraction v = new Fraction(a * d + b * c, b * d);
return v;
}
public Fraction sub(Fraction rFrac) {
int a = this.numer;
int b = this.denom;
int c = rFrac.numer;
int d = rFrac.denom;
Fraction v = new Fraction(a * d - b * c, b * d);
return v;
}
public Fraction mult(Fraction rFrac) {
int a = this.numer;
int b = this.denom;
int c = rFrac.numer;
int d = rFrac.denom;
Fraction v = new Fraction(a * c, b * d);
return v;
}
public Fraction div(Fraction rFrac) {
int a = this.numer;
int b = this.denom;
int c = rFrac.numer;
int d = rFrac.denom;
Fraction v = new Fraction(a * d, b * c);
return v;
}
public boolean isSimplestForm() {
return gcd(numer, denom) == 1;
}
public Fraction reduce() {
int i = gcd(numer, denom);
return new Fraction(numer/i, denom/i);
}
public boolean properFrac() {
return gcd(numer, denom) == 1;
}
public Fraction abs() {
int int1 = numer;
int int2 = denom;
// if any of two numbers are negative, make it positive
if(int1 < 0)
int1 = -int1;
if(int2 < 0)
int2 = -int2;
return new Fraction(int1, int2);
}
public boolean lessThan(Fraction rFrac) {
return convertToDecimal() < rFrac.convertToDecimal();
}
public boolean greaterThan(Fraction rFrac) {
return convertToDecimal() > rFrac.convertToDecimal();
}
public double convertToDecimal() {
return (double)numer/(double)denom;
}
public Fraction invert() {
return new Fraction(denom, numer);
}
private int gcd(int int1, int int2) {
int i = 0;
int smallest=0;
// if any of two numbers are negative, make it positive
if(int1 < 0)
int1 = -int1;
if(int2 < 0)
int2 = -int2;
if (int2>0){
if (int1 < int2) {
smallest=int1;
}
else{
smallest= int2;
}
for (i = smallest; i > 0; i--) {
if ((int1 % i == 0) && (int2 % i == 0)) {
break;
}
}
}
return i;
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class FractionDrive {
public static void main(String[] args) {
int numer, denom;
Fraction frac1;
Scanner input = new Scanner(System.in);
Boolean valid_input = false;
while (!valid_input) try {
System.out.print("Enter numerator denominator: ");
numer = input.nextInt();
denom = input.nextInt();
frac1 = new Fraction(numer,denom);
valid_input = true;
System.out.println(frac1);
}
catch (InvalidDenominatorException e) {
System.out.println("Denominator of Zero found – Please reenter");
}
catch (InputMismatchException e) {
System.out.println("Non-digit character found – Please reenter");
}
}
}
/*
Sample run:
Enter numerator denominator: 1 0
Denominator of Zero found – Please reenter
Enter numerator denominator: 0 2
0/2
*/

More Related Content

Similar to PROGRAM 2 – Fraction Class Problem For this programming as.pdf

Java Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdfJava Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdfaroramobiles1
 
Help in JAVAThis program should input numerator and denominator f.pdf
Help in JAVAThis program should input numerator and denominator f.pdfHelp in JAVAThis program should input numerator and denominator f.pdf
Help in JAVAThis program should input numerator and denominator f.pdfmanjan6
 
import java.util.Scanner;public class Fraction {   instan.pdf
import java.util.Scanner;public class Fraction {    instan.pdfimport java.util.Scanner;public class Fraction {    instan.pdf
import java.util.Scanner;public class Fraction {   instan.pdfapleathers
 
Import java
Import javaImport java
Import javaheni2121
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5alish sha
 
Fraction.h #include iostream #ifndef FRACTION #define FR.pdf
Fraction.h #include iostream #ifndef FRACTION #define FR.pdfFraction.h #include iostream #ifndef FRACTION #define FR.pdf
Fraction.h #include iostream #ifndef FRACTION #define FR.pdfravikapoorindia
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003R696
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfanukoolelectronics
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdfexxonzone
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++Seok-joon Yun
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7Rumman Ansari
 

Similar to PROGRAM 2 – Fraction Class Problem For this programming as.pdf (20)

Java Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdfJava Programpublic class Fraction {   instance variablesin.pdf
Java Programpublic class Fraction {   instance variablesin.pdf
 
Help in JAVAThis program should input numerator and denominator f.pdf
Help in JAVAThis program should input numerator and denominator f.pdfHelp in JAVAThis program should input numerator and denominator f.pdf
Help in JAVAThis program should input numerator and denominator f.pdf
 
JAVA Write a class called F.pdf
JAVA  Write a class called F.pdfJAVA  Write a class called F.pdf
JAVA Write a class called F.pdf
 
import java.util.Scanner;public class Fraction {   instan.pdf
import java.util.Scanner;public class Fraction {    instan.pdfimport java.util.Scanner;public class Fraction {    instan.pdf
import java.util.Scanner;public class Fraction {   instan.pdf
 
Import java
Import javaImport java
Import java
 
Dti2143 chapter 5
Dti2143 chapter 5Dti2143 chapter 5
Dti2143 chapter 5
 
Fraction.h #include iostream #ifndef FRACTION #define FR.pdf
Fraction.h #include iostream #ifndef FRACTION #define FR.pdfFraction.h #include iostream #ifndef FRACTION #define FR.pdf
Fraction.h #include iostream #ifndef FRACTION #define FR.pdf
 
Function in c
Function in cFunction in c
Function in c
 
Clean code _v2003
 Clean code _v2003 Clean code _v2003
Clean code _v2003
 
7 functions
7  functions7  functions
7 functions
 
functions
functionsfunctions
functions
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
 
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf#ifndef RATIONAL_H    if this compiler macro is not defined #def.pdf
#ifndef RATIONAL_H   if this compiler macro is not defined #def.pdf
 
Functions
FunctionsFunctions
Functions
 
Function in c
Function in cFunction in c
Function in c
 
Welcome to Modern C++
Welcome to Modern C++Welcome to Modern C++
Welcome to Modern C++
 
Unit 4 (1)
Unit 4 (1)Unit 4 (1)
Unit 4 (1)
 
C Programming Language Part 7
C Programming Language Part 7C Programming Language Part 7
C Programming Language Part 7
 
Estructura secuencial -garcia
Estructura secuencial -garciaEstructura secuencial -garcia
Estructura secuencial -garcia
 
function_v1.ppt
function_v1.pptfunction_v1.ppt
function_v1.ppt
 

More from ezonesolutions

hi need help with this question, ignore the circles (f) Indicate .pdf
hi need help with this question, ignore the circles (f) Indicate .pdfhi need help with this question, ignore the circles (f) Indicate .pdf
hi need help with this question, ignore the circles (f) Indicate .pdfezonesolutions
 
Explain TWO examples of fungal interactions with other speciesSo.pdf
Explain TWO examples of fungal interactions with other speciesSo.pdfExplain TWO examples of fungal interactions with other speciesSo.pdf
Explain TWO examples of fungal interactions with other speciesSo.pdfezonesolutions
 
DNA replicationTranscriptionTranslationPurposeWhere it occur.pdf
DNA replicationTranscriptionTranslationPurposeWhere it occur.pdfDNA replicationTranscriptionTranslationPurposeWhere it occur.pdf
DNA replicationTranscriptionTranslationPurposeWhere it occur.pdfezonesolutions
 
Does Microsoft directly disclose LinkedIn revenue for 2016 Explain .pdf
Does Microsoft directly disclose LinkedIn revenue for 2016 Explain .pdfDoes Microsoft directly disclose LinkedIn revenue for 2016 Explain .pdf
Does Microsoft directly disclose LinkedIn revenue for 2016 Explain .pdfezonesolutions
 
continuous, analytic, differentiableWhat is the relationship betwe.pdf
continuous, analytic, differentiableWhat is the relationship betwe.pdfcontinuous, analytic, differentiableWhat is the relationship betwe.pdf
continuous, analytic, differentiableWhat is the relationship betwe.pdfezonesolutions
 
Define the types of ultrasound pressure wavesSolutionUltrasoun.pdf
Define the types of ultrasound pressure wavesSolutionUltrasoun.pdfDefine the types of ultrasound pressure wavesSolutionUltrasoun.pdf
Define the types of ultrasound pressure wavesSolutionUltrasoun.pdfezonesolutions
 
Consider the current national debate about the revelation that top g.pdf
Consider the current national debate about the revelation that top g.pdfConsider the current national debate about the revelation that top g.pdf
Consider the current national debate about the revelation that top g.pdfezonesolutions
 
Case Study UrolithiasisCase PresentationDaniel, a thirty-two ye.pdf
Case Study UrolithiasisCase PresentationDaniel, a thirty-two ye.pdfCase Study UrolithiasisCase PresentationDaniel, a thirty-two ye.pdf
Case Study UrolithiasisCase PresentationDaniel, a thirty-two ye.pdfezonesolutions
 
A recombinant DNA was constructed by inserting the DNA of interest i.pdf
A recombinant DNA was constructed by inserting the DNA of interest i.pdfA recombinant DNA was constructed by inserting the DNA of interest i.pdf
A recombinant DNA was constructed by inserting the DNA of interest i.pdfezonesolutions
 
A conductor of length l lies along the x axis with current I in the +.pdf
A conductor of length l lies along the x axis with current I in the +.pdfA conductor of length l lies along the x axis with current I in the +.pdf
A conductor of length l lies along the x axis with current I in the +.pdfezonesolutions
 
What are the main motives for establishing an international joint ve.pdf
What are the main motives for establishing an international joint ve.pdfWhat are the main motives for establishing an international joint ve.pdf
What are the main motives for establishing an international joint ve.pdfezonesolutions
 
9 & 10 9. The study of behavioral finance has best helped explain .pdf
9 & 10 9. The study of behavioral finance has best helped explain .pdf9 & 10 9. The study of behavioral finance has best helped explain .pdf
9 & 10 9. The study of behavioral finance has best helped explain .pdfezonesolutions
 
Will Chinas economic success continue into the foreseeable future.pdf
Will Chinas economic success continue into the foreseeable future.pdfWill Chinas economic success continue into the foreseeable future.pdf
Will Chinas economic success continue into the foreseeable future.pdfezonesolutions
 
Which of the following ions would exhibit the greatest conductivity.pdf
Which of the following ions would exhibit the greatest conductivity.pdfWhich of the following ions would exhibit the greatest conductivity.pdf
Which of the following ions would exhibit the greatest conductivity.pdfezonesolutions
 
Which fault-tolerant-like system can back up media in much the same .pdf
Which fault-tolerant-like system can back up media in much the same .pdfWhich fault-tolerant-like system can back up media in much the same .pdf
Which fault-tolerant-like system can back up media in much the same .pdfezonesolutions
 
When may a federal court hear a caseSolutionFederal Court wil.pdf
When may a federal court hear a caseSolutionFederal Court wil.pdfWhen may a federal court hear a caseSolutionFederal Court wil.pdf
When may a federal court hear a caseSolutionFederal Court wil.pdfezonesolutions
 
4) Production in the country of StockVille can be characterized by th.pdf
4) Production in the country of StockVille can be characterized by th.pdf4) Production in the country of StockVille can be characterized by th.pdf
4) Production in the country of StockVille can be characterized by th.pdfezonesolutions
 
What is the pre-order traversal sequence for the above treeSolut.pdf
What is the pre-order traversal sequence for the above treeSolut.pdfWhat is the pre-order traversal sequence for the above treeSolut.pdf
What is the pre-order traversal sequence for the above treeSolut.pdfezonesolutions
 
Show that the class P, viewed as a set of languages is closed under c.pdf
Show that the class P, viewed as a set of languages is closed under c.pdfShow that the class P, viewed as a set of languages is closed under c.pdf
Show that the class P, viewed as a set of languages is closed under c.pdfezonesolutions
 
Related to Making the Connection] In the court case over whether any.pdf
Related to Making the Connection] In the court case over whether any.pdfRelated to Making the Connection] In the court case over whether any.pdf
Related to Making the Connection] In the court case over whether any.pdfezonesolutions
 

More from ezonesolutions (20)

hi need help with this question, ignore the circles (f) Indicate .pdf
hi need help with this question, ignore the circles (f) Indicate .pdfhi need help with this question, ignore the circles (f) Indicate .pdf
hi need help with this question, ignore the circles (f) Indicate .pdf
 
Explain TWO examples of fungal interactions with other speciesSo.pdf
Explain TWO examples of fungal interactions with other speciesSo.pdfExplain TWO examples of fungal interactions with other speciesSo.pdf
Explain TWO examples of fungal interactions with other speciesSo.pdf
 
DNA replicationTranscriptionTranslationPurposeWhere it occur.pdf
DNA replicationTranscriptionTranslationPurposeWhere it occur.pdfDNA replicationTranscriptionTranslationPurposeWhere it occur.pdf
DNA replicationTranscriptionTranslationPurposeWhere it occur.pdf
 
Does Microsoft directly disclose LinkedIn revenue for 2016 Explain .pdf
Does Microsoft directly disclose LinkedIn revenue for 2016 Explain .pdfDoes Microsoft directly disclose LinkedIn revenue for 2016 Explain .pdf
Does Microsoft directly disclose LinkedIn revenue for 2016 Explain .pdf
 
continuous, analytic, differentiableWhat is the relationship betwe.pdf
continuous, analytic, differentiableWhat is the relationship betwe.pdfcontinuous, analytic, differentiableWhat is the relationship betwe.pdf
continuous, analytic, differentiableWhat is the relationship betwe.pdf
 
Define the types of ultrasound pressure wavesSolutionUltrasoun.pdf
Define the types of ultrasound pressure wavesSolutionUltrasoun.pdfDefine the types of ultrasound pressure wavesSolutionUltrasoun.pdf
Define the types of ultrasound pressure wavesSolutionUltrasoun.pdf
 
Consider the current national debate about the revelation that top g.pdf
Consider the current national debate about the revelation that top g.pdfConsider the current national debate about the revelation that top g.pdf
Consider the current national debate about the revelation that top g.pdf
 
Case Study UrolithiasisCase PresentationDaniel, a thirty-two ye.pdf
Case Study UrolithiasisCase PresentationDaniel, a thirty-two ye.pdfCase Study UrolithiasisCase PresentationDaniel, a thirty-two ye.pdf
Case Study UrolithiasisCase PresentationDaniel, a thirty-two ye.pdf
 
A recombinant DNA was constructed by inserting the DNA of interest i.pdf
A recombinant DNA was constructed by inserting the DNA of interest i.pdfA recombinant DNA was constructed by inserting the DNA of interest i.pdf
A recombinant DNA was constructed by inserting the DNA of interest i.pdf
 
A conductor of length l lies along the x axis with current I in the +.pdf
A conductor of length l lies along the x axis with current I in the +.pdfA conductor of length l lies along the x axis with current I in the +.pdf
A conductor of length l lies along the x axis with current I in the +.pdf
 
What are the main motives for establishing an international joint ve.pdf
What are the main motives for establishing an international joint ve.pdfWhat are the main motives for establishing an international joint ve.pdf
What are the main motives for establishing an international joint ve.pdf
 
9 & 10 9. The study of behavioral finance has best helped explain .pdf
9 & 10 9. The study of behavioral finance has best helped explain .pdf9 & 10 9. The study of behavioral finance has best helped explain .pdf
9 & 10 9. The study of behavioral finance has best helped explain .pdf
 
Will Chinas economic success continue into the foreseeable future.pdf
Will Chinas economic success continue into the foreseeable future.pdfWill Chinas economic success continue into the foreseeable future.pdf
Will Chinas economic success continue into the foreseeable future.pdf
 
Which of the following ions would exhibit the greatest conductivity.pdf
Which of the following ions would exhibit the greatest conductivity.pdfWhich of the following ions would exhibit the greatest conductivity.pdf
Which of the following ions would exhibit the greatest conductivity.pdf
 
Which fault-tolerant-like system can back up media in much the same .pdf
Which fault-tolerant-like system can back up media in much the same .pdfWhich fault-tolerant-like system can back up media in much the same .pdf
Which fault-tolerant-like system can back up media in much the same .pdf
 
When may a federal court hear a caseSolutionFederal Court wil.pdf
When may a federal court hear a caseSolutionFederal Court wil.pdfWhen may a federal court hear a caseSolutionFederal Court wil.pdf
When may a federal court hear a caseSolutionFederal Court wil.pdf
 
4) Production in the country of StockVille can be characterized by th.pdf
4) Production in the country of StockVille can be characterized by th.pdf4) Production in the country of StockVille can be characterized by th.pdf
4) Production in the country of StockVille can be characterized by th.pdf
 
What is the pre-order traversal sequence for the above treeSolut.pdf
What is the pre-order traversal sequence for the above treeSolut.pdfWhat is the pre-order traversal sequence for the above treeSolut.pdf
What is the pre-order traversal sequence for the above treeSolut.pdf
 
Show that the class P, viewed as a set of languages is closed under c.pdf
Show that the class P, viewed as a set of languages is closed under c.pdfShow that the class P, viewed as a set of languages is closed under c.pdf
Show that the class P, viewed as a set of languages is closed under c.pdf
 
Related to Making the Connection] In the court case over whether any.pdf
Related to Making the Connection] In the court case over whether any.pdfRelated to Making the Connection] In the court case over whether any.pdf
Related to Making the Connection] In the court case over whether any.pdf
 

Recently uploaded

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 

Recently uploaded (20)

CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 

PROGRAM 2 – Fraction Class Problem For this programming as.pdf

  • 1. PROGRAM 2 – Fraction Class Problem For this programming assignment, you are to implement the Fraction class design given below (and discussed in class). You are also to develop an appropriate test driver that thoroughly tests the class. Fraction Class Design Implement the following class design. Make sure to use implement the methods to have the same names as given below, with the same number and types of parameters. public class Fraction { private int numer; private int denom; // alternate constructor public Fraction(int numer, int denom) throws InvalidDenominatorException { } // copy constructor public Fraction(Fraction otherFrac) { } // getters public int getNumer() { } public int getDenom() { } // standard methods public String toString() { } public boolean equals(Fraction rFrac) { } // fraction operators
  • 2. public Fraction add(Fraction rFrac) { } public Fraction sub(Fraction rFrac) { } public Fraction mult(Fraction rFrac) { } public Fraction div(Fraction rFrac) { } public boolean isSimplestForm() { } public Fraction reduce() { } public boolean properFrac() { } public Fraction abs() { } public boolean lessThan(Fraction rFrac) { } public boolean greaterThan(Fraction rFrac) { } public double convertToDecimal() { } public Fraction invert() { } } Note that objects of type Fraction are immutable. Also, the alternate constructor throws an InvalidDenominatorException if passed a denominator value of 0. This exception type is not predefined in Java, so you must define it as follow as another class in your Java project files: public class InvalidDenominatorException extends RuntimeException { } // nothing to implement This creates an exception of type RuntimeException. RuntimeExceptions do not need to be caught when thrown. However, your test driver should have the code for catching this exception
  • 3. where appropriate. For example, if your test driver excutes the following, Fraction frac1 = new Fraction(1,2); then there is no need to catch the possible exception, since it is clear that the denominator is not 0. However, if the value are input by the user, then there is a chance that a denominator vaue of 0 could be entered, and therefore the code for catching the possible exception is needed, int numer, denom; Fraction frac1; Scanner input = new Scanner(System.in); Boolean valid_input = false; while (!valid_input) try { System.out.print(“Enter numerator denominator: “); numer = input.nextInt(); denom = input.nextInt(); frac1 = new Fraction(numer,denom); valid_input = true; } catch (InvalidDenominatorException e) { System.out.println(“Denominator of Zero found – Please reenter”); } catch (InputMismatchException e) { System.out.println(“Non-digit character found – Please reenter”); } etc. Considerations Makes sure the equals method returns true for any two fractions that are arithmetically equal. Make sure that the equals, lessThan and greaterThan methods do not alter the values of the fractions being compared. You may consider the use of private methods that are called by the public methods of the class, but not accessible to the users (“client code”).
  • 4. Solution Hi, Please find my implementation. Please let me know in case of any issue. public class Fraction { private int numer; private int denom; // alternate constructor public Fraction(int numer, int denom) throws InvalidDenominatorException{ if(denom == 0) throw new InvalidDenominatorException(); this.numer = numer; this.denom = denom; } // copy constructor public Fraction(Fraction otherFrac) { numer = otherFrac.numer; denom = otherFrac.denom; } // getters public int getNumer() { return numer; } public int getDenom() { return denom; } // standard methods public String toString() { int n = numer; int d = denom; if(d < 0){ n = -n; // converting n as negative d = -d; // converting d as positive } if(d == 1) return Integer.toString(n);
  • 5. return n + "/" + d; } public boolean equals(Fraction rFrac) { return convertToDecimal() == rFrac.convertToDecimal(); } // fraction operators public Fraction add(Fraction rFrac) { int a = this.numer; int b = this.denom; int c = rFrac.numer; int d = rFrac.denom; Fraction v = new Fraction(a * d + b * c, b * d); return v; } public Fraction sub(Fraction rFrac) { int a = this.numer; int b = this.denom; int c = rFrac.numer; int d = rFrac.denom; Fraction v = new Fraction(a * d - b * c, b * d); return v; } public Fraction mult(Fraction rFrac) { int a = this.numer; int b = this.denom; int c = rFrac.numer; int d = rFrac.denom; Fraction v = new Fraction(a * c, b * d); return v; } public Fraction div(Fraction rFrac) { int a = this.numer; int b = this.denom; int c = rFrac.numer;
  • 6. int d = rFrac.denom; Fraction v = new Fraction(a * d, b * c); return v; } public boolean isSimplestForm() { return gcd(numer, denom) == 1; } public Fraction reduce() { int i = gcd(numer, denom); return new Fraction(numer/i, denom/i); } public boolean properFrac() { return gcd(numer, denom) == 1; } public Fraction abs() { int int1 = numer; int int2 = denom; // if any of two numbers are negative, make it positive if(int1 < 0) int1 = -int1; if(int2 < 0) int2 = -int2; return new Fraction(int1, int2); } public boolean lessThan(Fraction rFrac) { return convertToDecimal() < rFrac.convertToDecimal(); } public boolean greaterThan(Fraction rFrac) { return convertToDecimal() > rFrac.convertToDecimal(); } public double convertToDecimal() { return (double)numer/(double)denom; }
  • 7. public Fraction invert() { return new Fraction(denom, numer); } private int gcd(int int1, int int2) { int i = 0; int smallest=0; // if any of two numbers are negative, make it positive if(int1 < 0) int1 = -int1; if(int2 < 0) int2 = -int2; if (int2>0){ if (int1 < int2) { smallest=int1; } else{ smallest= int2; } for (i = smallest; i > 0; i--) { if ((int1 % i == 0) && (int2 % i == 0)) { break; } } } return i; } } import java.util.InputMismatchException; import java.util.Scanner; public class FractionDrive { public static void main(String[] args) { int numer, denom; Fraction frac1; Scanner input = new Scanner(System.in);
  • 8. Boolean valid_input = false; while (!valid_input) try { System.out.print("Enter numerator denominator: "); numer = input.nextInt(); denom = input.nextInt(); frac1 = new Fraction(numer,denom); valid_input = true; System.out.println(frac1); } catch (InvalidDenominatorException e) { System.out.println("Denominator of Zero found – Please reenter"); } catch (InputMismatchException e) { System.out.println("Non-digit character found – Please reenter"); } } } /* Sample run: Enter numerator denominator: 1 0 Denominator of Zero found – Please reenter Enter numerator denominator: 0 2 0/2 */