SlideShare a Scribd company logo
1 of 8
Download to read offline
Help in JAVA:
This program should input numerator and denominator from a file, create a Fraction object
(reducing the fraction if necessary) and then save the fraction to an ArrayList. This list will then
be sorted, and output.
Make one method to input, create, and add to the ArrayList. Another method call to sort. And the
third method to output the contents of the (sorted) ArrayList.
The input file will consist of an (unknown) quantity of ints representing numerator denominator
pairs, which may be negative or zero.
You will need to think about your constructor - you will find it easier if you follow these rules
1. If both numerator and denominator are negative make them both positive
2. if the numerator is positive but the denominator is negative switch both so that the numerator
is negative and the denominator positive
3. any other case leave as is.
what I have so far:
public static class Fraction {
private int numerator;
private int denominator;
public Fraction() {
numerator = 0;
denominator = 1;
}
public Fraction(int n, int d) {
int g = gcd(n, d);
numerator = n/g;
denominator = d/g;
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int n) {
int d = denominator;
int g = gcd(n, d);
numerator = n / g;
denominator= d/g;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int d) {
int n = numerator;
int g = gcd(n, d);
denominator = d / g;
numerator= n/g;
}
public Fraction add(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d + b * c, b * d);
return v;
}
public Fraction subtract(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d - b * c, b * d);
return v;
}
public Fraction multiply(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * c, b * d);
return v;
}
public Fraction divide(Fraction g) {
int a = this.numerator;
int b = this.denominator;
int c = g.numerator;
int d = g.denominator;
Fraction v = new Fraction(a * d, b * c);
return v;
}
public String toString() {
return numerator + "/" + denominator;
}
private int gcd(int int1, int int2) {
int i = 0;
int smallest=0;
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;
}
public int input(){
File inFile = new File("h7.txt");
Scanner fileInput = null;
try {
fileInput = new Scanner(inFile);
} catch (FileNotFoundException ex) {
}
fileInput.nextInt();
}
public int sort(int input){
Collections.sort();
}
public int output(){
System.out.println();
}
}
public static void main(String[] args) {
}
}
Solution
Fraction class is used to represents fractions. It is always used to reduced to lowest terms.If
fraction is negative then the numerator will always be negative and all operators leave results
which is to be stored in lowest terms.
In this Class is not complete, only addition operation is implemented.
Here is the program with some modification:
import java.util.*;
import java.lang.*;
import java.io.*;
public class Fraction {
private int numerator; // Fraction numerator
private int denominator; // Fraction denominator
/*-----------------------------------------------------------------
* constructor
* Takes no parameters, initializes the object to 0/1
*/
public Fraction() {
numerator = 0;
denominator = 1;
}
/*-----------------------------------------------------------------
* constructor
* Takes parameter, the numerator, initializes denominator to 1
* so object is numerator/1
*/
public Fraction(int num) {
numerator = num;
denominator = 1;
}
/*-----------------------------------------------------------------
* constructor
* If fraction is negative, put negative number in numerator
*/
public Fraction(int num, int denom) {
numerator = (denom < 0 ? -num : num);
if (denom == 0) {
denominator = 1;
}
denominator = (denom < 0 ? -denom : denom);
reduce();
}
/*-----------------------------------------------------------------
* setNumerator
* numerator is set to be the given parameter
*/
public void setNumerator(int num) {
numerator = num;
reduce();
}
/*-----------------------------------------------------------------
* getNumerator
* return numerator
*/
public int getNumerator() {
return numerator;
}
/*-----------------------------------------------------------------
* setDenominator
* denominator is set to be the given parameter (zero is ignored),
* if denominator is negative, numerator is adjusted
*/
public void setDenominator(int denom) {
if (denom > 0) {
denominator = denom;
reduce();
}
else if (denom < 0) {
numerator = -numerator;
denominator = -denom;
reduce();
}
}
/*-----------------------------------------------------------------
* getDenominator
* return denominator
*/
public int getDenominator() {
return denominator;
}
/*-----------------------------------------------------------------
* addTo
* add the parameter Fraction to the current object Fraction
*/
public Fraction addTo(Fraction rhs) {
Fraction sum = new Fraction();
sum.denominator = denominator * rhs.denominator;
sum.numerator = numerator * rhs.denominator
+ denominator * rhs.numerator;
sum.reduce();
return sum;
}
/*-----------------------------------------------------------------
* toString
* convert the Fraction to a String object, e.g., 2/3
*/
public String toString() {
return numerator + "/" + denominator;
}
/*-----------------------------------------------------------------
* equals
* compare the parameter Fraction to the current object Fraction
*/
public boolean equals(Fraction rhs) {
return (numerator == rhs.numerator) && (denominator == rhs.denominator);
}
/*-----------------------------------------------------------------
* reduce
* reduce Fraction to lowest terms by finding largest common denominator
* and dividing it out
*/
private void reduce() {
// find the larger of the numerator and denominator
int n = numerator, d = denominator, largest;
if (numerator < 0) {
n = -numerator;
}
if (n > d) {
largest = n;
}
else {
largest = d;
}
// find the largest number that divide the numerator and
// denominator evenly
int gcd = 0;
for (int i = largest; i >= 2; i--) {
if (numerator % i == 0 && denominator % i == 0) {
gcd = i;
break;
}
}
// divide the largest common denominator out of numerator, denominator
if (gcd != 0) {
numerator /= gcd;
denominator /= gcd;
}
}
}

More Related Content

Similar to Help in JAVAThis program should input numerator and denominator f.pdf

Cambio de bases
Cambio de basesCambio de bases
Cambio de basesalcon2015
 
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.pdfvinaythemodel
 
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 .pdfjyothimuppasani1
 
Here is the code with comments to solve the question. Please do rate.pdf
Here is the code with comments to solve the question. Please do rate.pdfHere is the code with comments to solve the question. Please do rate.pdf
Here is the code with comments to solve the question. Please do rate.pdfangelfragranc
 
Part 1 - Written AnswersDownload the GridWriter.zip file and exami.pdf
Part 1 - Written AnswersDownload the GridWriter.zip file and exami.pdfPart 1 - Written AnswersDownload the GridWriter.zip file and exami.pdf
Part 1 - Written AnswersDownload the GridWriter.zip file and exami.pdfkamdinrossihoungma74
 
#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
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
 
Write a program that works with fractions. You are first to implemen.pdf
Write a program that works with fractions. You are first to implemen.pdfWrite a program that works with fractions. You are first to implemen.pdf
Write a program that works with fractions. You are first to implemen.pdfleventhalbrad49439
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfmichardsonkhaicarr37
 
Write a function which return a list of all of the n element subset .pdf
Write a function which return a list of all of the n element subset .pdfWrite a function which return a list of all of the n element subset .pdf
Write a function which return a list of all of the n element subset .pdfhardjasonoco14599
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingHariz Mustafa
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfcontact41
 

Similar to Help in JAVAThis program should input numerator and denominator f.pdf (20)

Cambio de bases
Cambio de basesCambio de bases
Cambio de bases
 
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
 
Overloading
OverloadingOverloading
Overloading
 
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
 
Here is the code with comments to solve the question. Please do rate.pdf
Here is the code with comments to solve the question. Please do rate.pdfHere is the code with comments to solve the question. Please do rate.pdf
Here is the code with comments to solve the question. Please do rate.pdf
 
Computer Network Assignment Help
Computer Network Assignment HelpComputer Network Assignment Help
Computer Network Assignment Help
 
Part 1 - Written AnswersDownload the GridWriter.zip file and exami.pdf
Part 1 - Written AnswersDownload the GridWriter.zip file and exami.pdfPart 1 - Written AnswersDownload the GridWriter.zip file and exami.pdf
Part 1 - Written AnswersDownload the GridWriter.zip file and exami.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
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
Write a program that works with fractions. You are first to implemen.pdf
Write a program that works with fractions. You are first to implemen.pdfWrite a program that works with fractions. You are first to implemen.pdf
Write a program that works with fractions. You are first to implemen.pdf
 
Lecture5
Lecture5Lecture5
Lecture5
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
Estructura secuencial -garcia
Estructura secuencial -garciaEstructura secuencial -garcia
Estructura secuencial -garcia
 
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
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
Write a function which return a list of all of the n element subset .pdf
Write a function which return a list of all of the n element subset .pdfWrite a function which return a list of all of the n element subset .pdf
Write a function which return a list of all of the n element subset .pdf
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
 
In this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdfIn this lab, we will write an application to store a deck of cards i.pdf
In this lab, we will write an application to store a deck of cards i.pdf
 
Functions
FunctionsFunctions
Functions
 

More from manjan6

An introduction and explanation of human factors and sociotechnical .pdf
An introduction and explanation of human factors and sociotechnical .pdfAn introduction and explanation of human factors and sociotechnical .pdf
An introduction and explanation of human factors and sociotechnical .pdfmanjan6
 
Astronomers were able to find a new planet in a far away solar system.pdf
Astronomers were able to find a new planet in a far away solar system.pdfAstronomers were able to find a new planet in a far away solar system.pdf
Astronomers were able to find a new planet in a far away solar system.pdfmanjan6
 
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdfmanjan6
 
All of the following individuals are U.S. residents Kelly (27.pdf
All of the following individuals are U.S. residents Kelly (27.pdfAll of the following individuals are U.S. residents Kelly (27.pdf
All of the following individuals are U.S. residents Kelly (27.pdfmanjan6
 
Blossom Company had these transactions during the current period..pdf
Blossom Company had these transactions during the current period..pdfBlossom Company had these transactions during the current period..pdf
Blossom Company had these transactions during the current period..pdfmanjan6
 
Using the case study below, develop a written report of your market .pdf
Using the case study below, develop a written report of your market .pdfUsing the case study below, develop a written report of your market .pdf
Using the case study below, develop a written report of your market .pdfmanjan6
 
Which of the following is NOT a characteristic of a plasmid used as .pdf
Which of the following is NOT a characteristic of a plasmid used as .pdfWhich of the following is NOT a characteristic of a plasmid used as .pdf
Which of the following is NOT a characteristic of a plasmid used as .pdfmanjan6
 
What is the evolutionary significance of the amniotic egg Solut.pdf
What is the evolutionary significance of the amniotic egg  Solut.pdfWhat is the evolutionary significance of the amniotic egg  Solut.pdf
What is the evolutionary significance of the amniotic egg Solut.pdfmanjan6
 
What is the role of HTTP What types of objects are transmitted in H.pdf
What is the role of HTTP What types of objects are transmitted in H.pdfWhat is the role of HTTP What types of objects are transmitted in H.pdf
What is the role of HTTP What types of objects are transmitted in H.pdfmanjan6
 
What is the difference between a hash in perl and a hashtable in Jav.pdf
What is the difference between a hash in perl and a hashtable in Jav.pdfWhat is the difference between a hash in perl and a hashtable in Jav.pdf
What is the difference between a hash in perl and a hashtable in Jav.pdfmanjan6
 
What are the specific linkages among immune surveillance, clonal sel.pdf
What are the specific linkages among immune surveillance, clonal sel.pdfWhat are the specific linkages among immune surveillance, clonal sel.pdf
What are the specific linkages among immune surveillance, clonal sel.pdfmanjan6
 
True or False –Paraeducators provide direct or indirect instructio.pdf
True or False –Paraeducators provide direct or indirect instructio.pdfTrue or False –Paraeducators provide direct or indirect instructio.pdf
True or False –Paraeducators provide direct or indirect instructio.pdfmanjan6
 
The situation where the few who yell the loudest get heard Is ref.pdf
The situation where the few who yell the loudest get heard Is ref.pdfThe situation where the few who yell the loudest get heard Is ref.pdf
The situation where the few who yell the loudest get heard Is ref.pdfmanjan6
 
Templated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdfTemplated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdfmanjan6
 
State if you agree or disagree with the question and comments made b.pdf
State if you agree or disagree with the question and comments made b.pdfState if you agree or disagree with the question and comments made b.pdf
State if you agree or disagree with the question and comments made b.pdfmanjan6
 
A number of benefits that one might expect to see from using a datab.pdf
A number of benefits that one might expect to see from using a datab.pdfA number of benefits that one might expect to see from using a datab.pdf
A number of benefits that one might expect to see from using a datab.pdfmanjan6
 
QUESTION If you look at the code, youll see that we keep two list.pdf
QUESTION If you look at the code, youll see that we keep two list.pdfQUESTION If you look at the code, youll see that we keep two list.pdf
QUESTION If you look at the code, youll see that we keep two list.pdfmanjan6
 
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdfQuestion 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdfmanjan6
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfmanjan6
 
Match the enzyme activity in DNA synthesis with its function. DNA po.pdf
Match the enzyme activity in DNA synthesis with its function.  DNA po.pdfMatch the enzyme activity in DNA synthesis with its function.  DNA po.pdf
Match the enzyme activity in DNA synthesis with its function. DNA po.pdfmanjan6
 

More from manjan6 (20)

An introduction and explanation of human factors and sociotechnical .pdf
An introduction and explanation of human factors and sociotechnical .pdfAn introduction and explanation of human factors and sociotechnical .pdf
An introduction and explanation of human factors and sociotechnical .pdf
 
Astronomers were able to find a new planet in a far away solar system.pdf
Astronomers were able to find a new planet in a far away solar system.pdfAstronomers were able to find a new planet in a far away solar system.pdf
Astronomers were able to find a new planet in a far away solar system.pdf
 
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
5. If we found AB+ blood at a crime scene and we knew one of our 5 s.pdf
 
All of the following individuals are U.S. residents Kelly (27.pdf
All of the following individuals are U.S. residents Kelly (27.pdfAll of the following individuals are U.S. residents Kelly (27.pdf
All of the following individuals are U.S. residents Kelly (27.pdf
 
Blossom Company had these transactions during the current period..pdf
Blossom Company had these transactions during the current period..pdfBlossom Company had these transactions during the current period..pdf
Blossom Company had these transactions during the current period..pdf
 
Using the case study below, develop a written report of your market .pdf
Using the case study below, develop a written report of your market .pdfUsing the case study below, develop a written report of your market .pdf
Using the case study below, develop a written report of your market .pdf
 
Which of the following is NOT a characteristic of a plasmid used as .pdf
Which of the following is NOT a characteristic of a plasmid used as .pdfWhich of the following is NOT a characteristic of a plasmid used as .pdf
Which of the following is NOT a characteristic of a plasmid used as .pdf
 
What is the evolutionary significance of the amniotic egg Solut.pdf
What is the evolutionary significance of the amniotic egg  Solut.pdfWhat is the evolutionary significance of the amniotic egg  Solut.pdf
What is the evolutionary significance of the amniotic egg Solut.pdf
 
What is the role of HTTP What types of objects are transmitted in H.pdf
What is the role of HTTP What types of objects are transmitted in H.pdfWhat is the role of HTTP What types of objects are transmitted in H.pdf
What is the role of HTTP What types of objects are transmitted in H.pdf
 
What is the difference between a hash in perl and a hashtable in Jav.pdf
What is the difference between a hash in perl and a hashtable in Jav.pdfWhat is the difference between a hash in perl and a hashtable in Jav.pdf
What is the difference between a hash in perl and a hashtable in Jav.pdf
 
What are the specific linkages among immune surveillance, clonal sel.pdf
What are the specific linkages among immune surveillance, clonal sel.pdfWhat are the specific linkages among immune surveillance, clonal sel.pdf
What are the specific linkages among immune surveillance, clonal sel.pdf
 
True or False –Paraeducators provide direct or indirect instructio.pdf
True or False –Paraeducators provide direct or indirect instructio.pdfTrue or False –Paraeducators provide direct or indirect instructio.pdf
True or False –Paraeducators provide direct or indirect instructio.pdf
 
The situation where the few who yell the loudest get heard Is ref.pdf
The situation where the few who yell the loudest get heard Is ref.pdfThe situation where the few who yell the loudest get heard Is ref.pdf
The situation where the few who yell the loudest get heard Is ref.pdf
 
Templated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdfTemplated Binary Tree implementing function help I need to im.pdf
Templated Binary Tree implementing function help I need to im.pdf
 
State if you agree or disagree with the question and comments made b.pdf
State if you agree or disagree with the question and comments made b.pdfState if you agree or disagree with the question and comments made b.pdf
State if you agree or disagree with the question and comments made b.pdf
 
A number of benefits that one might expect to see from using a datab.pdf
A number of benefits that one might expect to see from using a datab.pdfA number of benefits that one might expect to see from using a datab.pdf
A number of benefits that one might expect to see from using a datab.pdf
 
QUESTION If you look at the code, youll see that we keep two list.pdf
QUESTION If you look at the code, youll see that we keep two list.pdfQUESTION If you look at the code, youll see that we keep two list.pdf
QUESTION If you look at the code, youll see that we keep two list.pdf
 
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdfQuestion 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
Question 11 What is the volume of 17.0 grams of carbon dioxide gas if.pdf
 
Please help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdfPlease help with this. program must be written in C# .. All of the g.pdf
Please help with this. program must be written in C# .. All of the g.pdf
 
Match the enzyme activity in DNA synthesis with its function. DNA po.pdf
Match the enzyme activity in DNA synthesis with its function.  DNA po.pdfMatch the enzyme activity in DNA synthesis with its function.  DNA po.pdf
Match the enzyme activity in DNA synthesis with its function. DNA po.pdf
 

Recently uploaded

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
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
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
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
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
 
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
 
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
 
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
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 

Recently uploaded (20)

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
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.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
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
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🔝
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
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
 
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
 
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 ...
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 

Help in JAVAThis program should input numerator and denominator f.pdf

  • 1. Help in JAVA: This program should input numerator and denominator from a file, create a Fraction object (reducing the fraction if necessary) and then save the fraction to an ArrayList. This list will then be sorted, and output. Make one method to input, create, and add to the ArrayList. Another method call to sort. And the third method to output the contents of the (sorted) ArrayList. The input file will consist of an (unknown) quantity of ints representing numerator denominator pairs, which may be negative or zero. You will need to think about your constructor - you will find it easier if you follow these rules 1. If both numerator and denominator are negative make them both positive 2. if the numerator is positive but the denominator is negative switch both so that the numerator is negative and the denominator positive 3. any other case leave as is. what I have so far: public static class Fraction { private int numerator; private int denominator; public Fraction() { numerator = 0; denominator = 1; } public Fraction(int n, int d) { int g = gcd(n, d); numerator = n/g; denominator = d/g; } public int getNumerator() { return numerator; } public void setNumerator(int n) { int d = denominator; int g = gcd(n, d); numerator = n / g; denominator= d/g; }
  • 2. public int getDenominator() { return denominator; } public void setDenominator(int d) { int n = numerator; int g = gcd(n, d); denominator = d / g; numerator= n/g; } public Fraction add(Fraction g) { int a = this.numerator; int b = this.denominator; int c = g.numerator; int d = g.denominator; Fraction v = new Fraction(a * d + b * c, b * d); return v; } public Fraction subtract(Fraction g) { int a = this.numerator; int b = this.denominator; int c = g.numerator; int d = g.denominator; Fraction v = new Fraction(a * d - b * c, b * d); return v; } public Fraction multiply(Fraction g) { int a = this.numerator; int b = this.denominator; int c = g.numerator; int d = g.denominator; Fraction v = new Fraction(a * c, b * d); return v; } public Fraction divide(Fraction g) { int a = this.numerator; int b = this.denominator;
  • 3. int c = g.numerator; int d = g.denominator; Fraction v = new Fraction(a * d, b * c); return v; } public String toString() { return numerator + "/" + denominator; } private int gcd(int int1, int int2) { int i = 0; int smallest=0; 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; } public int input(){ File inFile = new File("h7.txt"); Scanner fileInput = null; try { fileInput = new Scanner(inFile); } catch (FileNotFoundException ex) { } fileInput.nextInt();
  • 4. } public int sort(int input){ Collections.sort(); } public int output(){ System.out.println(); } } public static void main(String[] args) { } } Solution Fraction class is used to represents fractions. It is always used to reduced to lowest terms.If fraction is negative then the numerator will always be negative and all operators leave results which is to be stored in lowest terms. In this Class is not complete, only addition operation is implemented. Here is the program with some modification: import java.util.*; import java.lang.*; import java.io.*; public class Fraction { private int numerator; // Fraction numerator private int denominator; // Fraction denominator /*----------------------------------------------------------------- * constructor * Takes no parameters, initializes the object to 0/1 */ public Fraction() { numerator = 0; denominator = 1;
  • 5. } /*----------------------------------------------------------------- * constructor * Takes parameter, the numerator, initializes denominator to 1 * so object is numerator/1 */ public Fraction(int num) { numerator = num; denominator = 1; } /*----------------------------------------------------------------- * constructor * If fraction is negative, put negative number in numerator */ public Fraction(int num, int denom) { numerator = (denom < 0 ? -num : num); if (denom == 0) { denominator = 1; } denominator = (denom < 0 ? -denom : denom); reduce(); } /*----------------------------------------------------------------- * setNumerator * numerator is set to be the given parameter */ public void setNumerator(int num) { numerator = num; reduce(); } /*----------------------------------------------------------------- * getNumerator * return numerator */ public int getNumerator() { return numerator;
  • 6. } /*----------------------------------------------------------------- * setDenominator * denominator is set to be the given parameter (zero is ignored), * if denominator is negative, numerator is adjusted */ public void setDenominator(int denom) { if (denom > 0) { denominator = denom; reduce(); } else if (denom < 0) { numerator = -numerator; denominator = -denom; reduce(); } } /*----------------------------------------------------------------- * getDenominator * return denominator */ public int getDenominator() { return denominator; } /*----------------------------------------------------------------- * addTo * add the parameter Fraction to the current object Fraction */ public Fraction addTo(Fraction rhs) { Fraction sum = new Fraction(); sum.denominator = denominator * rhs.denominator; sum.numerator = numerator * rhs.denominator + denominator * rhs.numerator; sum.reduce(); return sum; }
  • 7. /*----------------------------------------------------------------- * toString * convert the Fraction to a String object, e.g., 2/3 */ public String toString() { return numerator + "/" + denominator; } /*----------------------------------------------------------------- * equals * compare the parameter Fraction to the current object Fraction */ public boolean equals(Fraction rhs) { return (numerator == rhs.numerator) && (denominator == rhs.denominator); } /*----------------------------------------------------------------- * reduce * reduce Fraction to lowest terms by finding largest common denominator * and dividing it out */ private void reduce() { // find the larger of the numerator and denominator int n = numerator, d = denominator, largest; if (numerator < 0) { n = -numerator; } if (n > d) { largest = n; } else { largest = d; } // find the largest number that divide the numerator and // denominator evenly int gcd = 0; for (int i = largest; i >= 2; i--) { if (numerator % i == 0 && denominator % i == 0) {
  • 8. gcd = i; break; } } // divide the largest common denominator out of numerator, denominator if (gcd != 0) { numerator /= gcd; denominator /= gcd; } } }