SlideShare a Scribd company logo
1 of 3
Download to read offline
*****************JAVA********************** Write a class called Fraction, which can
be used to store an exact fraction. It must have: - A field to store the numerator - A
field to store the denominator - A toString method that returns a neatly formatted String
representing the fraction - An equals method that compares itself to another Fraction -
An add method that adds itself to another Fraction and returns a new Fraction - Appropriate
constructor and accessors as needed Write a program that asks the user to enter the numerators
and denominators of two fractions and create corresponding Fraction objects. Check for valid
input and a 0 denominator. Then output both Fractions (using your toString method implicitly),
whether they are equal, and their sum. Name your main class Hw6pr2 and your file
Hw6pr2.java. Submit all .java files
Solution
import java.util.*;
import java.io.*;
public class Fraction
{
static Scanner console = new Scanner(System.in);
public static void main(String[] args);
private int numerator;
private int denominator;
System.out.println("Enter the denominator");
System.out.flush();
while(console.hasNext())
{
denominator = console.nextInt();
public String toString()
{
return (numerator + " / " + denominator);
}
public boolean equals(Fraction rightFr)
{
return(numerator * rightFr.denominator == denominator * rightFr.numerator);
}
public int compareTo(Fraction rightFr)
{
return(numerator * rightFr.denominator-denominator * rightFr.numerator);
}
public Fraction(int num, int deno) throws Exception
{
numerator = num;
if(deno == 0)
throw new Exception("denominator cannot be zero");
else
denominator = deno;
}
public Fraction()
{
numerator = 0;
denominator = 1;
}
public void setFraction(int num, int deno) throws Exception
{
numerator = num;
if(deno == 0)
throw new Exception("denominator cannot be zero");
else
denominator = deno;
}
public Fraction add(Fraction rightFr)
{
Fraction temp = new Fraction();
temp.numerator = numerator * rightFr.denominator + rightFr.numerator * denominator;
temp.denominator = denominator * rightFr.denominatior;
return temp;
}
public Fraction multiply(Fraction rightFr)
{
Fraction temp = new Fraction();
temp.numerator = numerator * rightFr.numerator;
temp.denominator = denominator * rightFr.denominator;
return temp;
}
public Fraction subtract(Fraction rightFr)
{
Fraction temp = new Fraction();
temp.numerator = numerator * rightFr. denominator-rightFr.numerator * denominator;
temp.denominator = denominator * rightFr.denominator;
retrun temp;
}
Fraction divide(Fraction rightFr) throws Exception
{
Fraction temp = new Fraction();
if(rightFr.numerator == 0)
throw new Exception("Cannot divide by zero");
else{
temp.numerator = numerator * rightFr.denominator;
temp.denominator = rightFr.numerator *denominator;
return temp;
}
System.out.println(" ");
System.out.println(" " +(numerator + denominator));
}
}

More Related Content

Similar to JAVA Write a class called F.pdf

How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
mail931892
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
mail931892
 
Digits.javapackage week04;import java.util.Scanner; public cla.pdf
Digits.javapackage week04;import java.util.Scanner; public cla.pdfDigits.javapackage week04;import java.util.Scanner; public cla.pdf
Digits.javapackage week04;import java.util.Scanner; public cla.pdf
annapurnnatextailes
 
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
 
Assignment 6 as a reference public class ArrExample pr.pdf
Assignment 6 as a reference   public class ArrExample    pr.pdfAssignment 6 as a reference   public class ArrExample    pr.pdf
Assignment 6 as a reference public class ArrExample pr.pdf
kksrivastava1
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
info114
 
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
 
Use the code below from the previous assignment that we need to exte.pdf
Use the code below from the previous assignment that we need to exte.pdfUse the code below from the previous assignment that we need to exte.pdf
Use the code below from the previous assignment that we need to exte.pdf
sales87
 
AnswerNote Provided code shows several bugs, hence I implemented.pdf
AnswerNote Provided code shows several bugs, hence I implemented.pdfAnswerNote Provided code shows several bugs, hence I implemented.pdf
AnswerNote Provided code shows several bugs, hence I implemented.pdf
anurag1231
 
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfAssignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
formicreation
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
stopgolook
 
operating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfoperating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdf
aquadreammail
 
When we test your Fraction.java we will use the given FractionTester.pdf
When we test your Fraction.java we will use the given FractionTester.pdfWhen we test your Fraction.java we will use the given FractionTester.pdf
When we test your Fraction.java we will use the given FractionTester.pdf
arihantkitchenmart
 
Main issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfMain issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdf
aonesalem
 

Similar to JAVA Write a class called F.pdf (20)

How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdfHow do I fix it in LinkedList.javathis is what i didLabProgra.pdf
How do I fix it in LinkedList.javathis is what i didLabProgra.pdf
 
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdfHow do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
How do I fix it in LinkedList.javaLabProgram.javaLinkedList.jav.pdf
 
C# labprograms
C# labprogramsC# labprograms
C# labprograms
 
Digits.javapackage week04;import java.util.Scanner; public cla.pdf
Digits.javapackage week04;import java.util.Scanner; public cla.pdfDigits.javapackage week04;import java.util.Scanner; public cla.pdf
Digits.javapackage week04;import java.util.Scanner; public cla.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
 
Assignment 6 as a reference public class ArrExample pr.pdf
Assignment 6 as a reference   public class ArrExample    pr.pdfAssignment 6 as a reference   public class ArrExample    pr.pdf
Assignment 6 as a reference public class ArrExample pr.pdf
 
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
 
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfNeed done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdf
 
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
 
Use the code below from the previous assignment that we need to exte.pdf
Use the code below from the previous assignment that we need to exte.pdfUse the code below from the previous assignment that we need to exte.pdf
Use the code below from the previous assignment that we need to exte.pdf
 
AnswerNote Provided code shows several bugs, hence I implemented.pdf
AnswerNote Provided code shows several bugs, hence I implemented.pdfAnswerNote Provided code shows several bugs, hence I implemented.pdf
AnswerNote Provided code shows several bugs, hence I implemented.pdf
 
Java execise
Java execiseJava execise
Java execise
 
Functional Programming with C#
Functional Programming with C#Functional Programming with C#
Functional Programming with C#
 
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdfAssignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
Assignment is Page 349-350 #4 and #5 Use the Linked Lis.pdf
 
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdfIn C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
In C++ please, do not alter node.hStep 1 Inspect the Node.h file.pdf
 
operating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdfoperating system linux,ubuntu,Mac Geometri.pdf
operating system linux,ubuntu,Mac Geometri.pdf
 
When we test your Fraction.java we will use the given FractionTester.pdf
When we test your Fraction.java we will use the given FractionTester.pdfWhen we test your Fraction.java we will use the given FractionTester.pdf
When we test your Fraction.java we will use the given FractionTester.pdf
 
Main issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdfMain issues with the following code-Im not sure if its reading the fil.pdf
Main issues with the following code-Im not sure if its reading the fil.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 

More from santanadenisesarin13

Thomas Lewis said “the capacity to blunder slightly is the real marv.pdf
Thomas Lewis said “the capacity to blunder slightly is the real marv.pdfThomas Lewis said “the capacity to blunder slightly is the real marv.pdf
Thomas Lewis said “the capacity to blunder slightly is the real marv.pdf
santanadenisesarin13
 
Q1. An individual who accepts the risks and opportunities entailed b.pdf
Q1. An individual who accepts the risks and opportunities entailed b.pdfQ1. An individual who accepts the risks and opportunities entailed b.pdf
Q1. An individual who accepts the risks and opportunities entailed b.pdf
santanadenisesarin13
 
Question 3 (24 markS) Westcock Shipbuilding Ltd. has a December 31 y.pdf
Question 3 (24 markS) Westcock Shipbuilding Ltd. has a December 31 y.pdfQuestion 3 (24 markS) Westcock Shipbuilding Ltd. has a December 31 y.pdf
Question 3 (24 markS) Westcock Shipbuilding Ltd. has a December 31 y.pdf
santanadenisesarin13
 
please help i have 40 minsItem 1In the case below, the original .pdf
please help i have 40 minsItem 1In the case below, the original .pdfplease help i have 40 minsItem 1In the case below, the original .pdf
please help i have 40 minsItem 1In the case below, the original .pdf
santanadenisesarin13
 
Need help writing Conways Game of Life. These are the instructions.pdf
Need help writing Conways Game of Life. These are the instructions.pdfNeed help writing Conways Game of Life. These are the instructions.pdf
Need help writing Conways Game of Life. These are the instructions.pdf
santanadenisesarin13
 
I need help with these two questions 4.12 and 4.13 dealing with MATL.pdf
I need help with these two questions 4.12 and 4.13 dealing with MATL.pdfI need help with these two questions 4.12 and 4.13 dealing with MATL.pdf
I need help with these two questions 4.12 and 4.13 dealing with MATL.pdf
santanadenisesarin13
 

More from santanadenisesarin13 (20)

What does it mean by mRNA coded for by the Operon What does it.pdf
What does it mean by mRNA coded for by the Operon What does it.pdfWhat does it mean by mRNA coded for by the Operon What does it.pdf
What does it mean by mRNA coded for by the Operon What does it.pdf
 
Variability of a sample can he measured use the following statistic(s.pdf
Variability of a sample can he measured use the following statistic(s.pdfVariability of a sample can he measured use the following statistic(s.pdf
Variability of a sample can he measured use the following statistic(s.pdf
 
What are the advantages of using a compiled language over an interpr.pdf
What are the advantages of using a compiled language over an interpr.pdfWhat are the advantages of using a compiled language over an interpr.pdf
What are the advantages of using a compiled language over an interpr.pdf
 
Unbiased estimators Let theta be an estimator of a parameter theta..pdf
Unbiased estimators  Let theta be an estimator of a parameter theta..pdfUnbiased estimators  Let theta be an estimator of a parameter theta..pdf
Unbiased estimators Let theta be an estimator of a parameter theta..pdf
 
Thomas Lewis said “the capacity to blunder slightly is the real marv.pdf
Thomas Lewis said “the capacity to blunder slightly is the real marv.pdfThomas Lewis said “the capacity to blunder slightly is the real marv.pdf
Thomas Lewis said “the capacity to blunder slightly is the real marv.pdf
 
The strongest attractive forces between molecules of H_2O are ionic.pdf
The strongest attractive forces between molecules of H_2O are  ionic.pdfThe strongest attractive forces between molecules of H_2O are  ionic.pdf
The strongest attractive forces between molecules of H_2O are ionic.pdf
 
Q1. An individual who accepts the risks and opportunities entailed b.pdf
Q1. An individual who accepts the risks and opportunities entailed b.pdfQ1. An individual who accepts the risks and opportunities entailed b.pdf
Q1. An individual who accepts the risks and opportunities entailed b.pdf
 
Question 3 (24 markS) Westcock Shipbuilding Ltd. has a December 31 y.pdf
Question 3 (24 markS) Westcock Shipbuilding Ltd. has a December 31 y.pdfQuestion 3 (24 markS) Westcock Shipbuilding Ltd. has a December 31 y.pdf
Question 3 (24 markS) Westcock Shipbuilding Ltd. has a December 31 y.pdf
 
Place the following formulas in their proper order A. ALE, residu.pdf
Place the following formulas in their proper order A. ALE, residu.pdfPlace the following formulas in their proper order A. ALE, residu.pdf
Place the following formulas in their proper order A. ALE, residu.pdf
 
please help i have 40 minsItem 1In the case below, the original .pdf
please help i have 40 minsItem 1In the case below, the original .pdfplease help i have 40 minsItem 1In the case below, the original .pdf
please help i have 40 minsItem 1In the case below, the original .pdf
 
Need help writing Conways Game of Life. These are the instructions.pdf
Need help writing Conways Game of Life. These are the instructions.pdfNeed help writing Conways Game of Life. These are the instructions.pdf
Need help writing Conways Game of Life. These are the instructions.pdf
 
Non-Euclidean GeometryWhat statement, if any, can be made about th.pdf
Non-Euclidean GeometryWhat statement, if any, can be made about th.pdfNon-Euclidean GeometryWhat statement, if any, can be made about th.pdf
Non-Euclidean GeometryWhat statement, if any, can be made about th.pdf
 
Java ProgrammingA Swing button can have more than one action liste.pdf
Java ProgrammingA Swing button can have more than one action liste.pdfJava ProgrammingA Swing button can have more than one action liste.pdf
Java ProgrammingA Swing button can have more than one action liste.pdf
 
In the adult, red bone marrow would normally be found in the sternu.pdf
In the adult, red bone marrow would normally be found in the  sternu.pdfIn the adult, red bone marrow would normally be found in the  sternu.pdf
In the adult, red bone marrow would normally be found in the sternu.pdf
 
I need help with these two questions 4.12 and 4.13 dealing with MATL.pdf
I need help with these two questions 4.12 and 4.13 dealing with MATL.pdfI need help with these two questions 4.12 and 4.13 dealing with MATL.pdf
I need help with these two questions 4.12 and 4.13 dealing with MATL.pdf
 
I dont understand the min and max Find the smallest positive value.pdf
I dont understand the min and max Find the smallest positive value.pdfI dont understand the min and max Find the smallest positive value.pdf
I dont understand the min and max Find the smallest positive value.pdf
 
How can the activation of effector molecules within cells be restric.pdf
How can the activation of effector molecules within cells be restric.pdfHow can the activation of effector molecules within cells be restric.pdf
How can the activation of effector molecules within cells be restric.pdf
 
Explain how the skin of reptiles adaptive for terrestial existence. .pdf
Explain how the skin of reptiles adaptive for terrestial existence. .pdfExplain how the skin of reptiles adaptive for terrestial existence. .pdf
Explain how the skin of reptiles adaptive for terrestial existence. .pdf
 
Distinguish the roles of the four economic actors in economicsSo.pdf
Distinguish the roles of the four economic actors in economicsSo.pdfDistinguish the roles of the four economic actors in economicsSo.pdf
Distinguish the roles of the four economic actors in economicsSo.pdf
 
Explain the term liquidity and how it relates to the classified bala.pdf
Explain the term liquidity and how it relates to the classified bala.pdfExplain the term liquidity and how it relates to the classified bala.pdf
Explain the term liquidity and how it relates to the classified bala.pdf
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
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
 

Recently uploaded (20)

PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
What is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptxWhat is 3 Way Matching Process in Odoo 17.pptx
What is 3 Way Matching Process in Odoo 17.pptx
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
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
 

JAVA Write a class called F.pdf

  • 1. *****************JAVA********************** Write a class called Fraction, which can be used to store an exact fraction. It must have: - A field to store the numerator - A field to store the denominator - A toString method that returns a neatly formatted String representing the fraction - An equals method that compares itself to another Fraction - An add method that adds itself to another Fraction and returns a new Fraction - Appropriate constructor and accessors as needed Write a program that asks the user to enter the numerators and denominators of two fractions and create corresponding Fraction objects. Check for valid input and a 0 denominator. Then output both Fractions (using your toString method implicitly), whether they are equal, and their sum. Name your main class Hw6pr2 and your file Hw6pr2.java. Submit all .java files Solution import java.util.*; import java.io.*; public class Fraction { static Scanner console = new Scanner(System.in); public static void main(String[] args); private int numerator; private int denominator; System.out.println("Enter the denominator"); System.out.flush(); while(console.hasNext()) { denominator = console.nextInt(); public String toString() { return (numerator + " / " + denominator); } public boolean equals(Fraction rightFr) { return(numerator * rightFr.denominator == denominator * rightFr.numerator); } public int compareTo(Fraction rightFr)
  • 2. { return(numerator * rightFr.denominator-denominator * rightFr.numerator); } public Fraction(int num, int deno) throws Exception { numerator = num; if(deno == 0) throw new Exception("denominator cannot be zero"); else denominator = deno; } public Fraction() { numerator = 0; denominator = 1; } public void setFraction(int num, int deno) throws Exception { numerator = num; if(deno == 0) throw new Exception("denominator cannot be zero"); else denominator = deno; } public Fraction add(Fraction rightFr) { Fraction temp = new Fraction(); temp.numerator = numerator * rightFr.denominator + rightFr.numerator * denominator; temp.denominator = denominator * rightFr.denominatior; return temp; } public Fraction multiply(Fraction rightFr) { Fraction temp = new Fraction(); temp.numerator = numerator * rightFr.numerator; temp.denominator = denominator * rightFr.denominator;
  • 3. return temp; } public Fraction subtract(Fraction rightFr) { Fraction temp = new Fraction(); temp.numerator = numerator * rightFr. denominator-rightFr.numerator * denominator; temp.denominator = denominator * rightFr.denominator; retrun temp; } Fraction divide(Fraction rightFr) throws Exception { Fraction temp = new Fraction(); if(rightFr.numerator == 0) throw new Exception("Cannot divide by zero"); else{ temp.numerator = numerator * rightFr.denominator; temp.denominator = rightFr.numerator *denominator; return temp; } System.out.println(" "); System.out.println(" " +(numerator + denominator)); } }