Question
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
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.
We need to start (again) writing modular code . 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 sofar:
import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner;
public class H7 { public static class Fractions implements Comparable
public void setNumerator(int n) { this.numerator=n; }
public int getDenominator() { return denominator; }
public void setDenominator(int d) { this.denominator=d; } //toString public String toString() { return numerator + "/" + denominator; } //Calculates greatest common factor private int gcd(int int1, int int2) { if ((int1 % int2) == 0) { return int2; } else{ return gcd(int2, int1 % int2); } } public int compareTo(Fractions f) { if (f.numerator return 1; else if (f.numerator==this.numerator && f.denominator==f.denominator) return 0; else return -1; } } public static void main(String[] args) { File inFile = new File("H7.txt"); Scanner fileInput = null; try { fileInput = new Scanner(inFile); } catch (FileNotFoundException ex) { } //create array ArrayList Input File: 6 9 10 100 -2 -1 -1 2 8 9 Output: 1/10 1/-2 2/3 2/1 8/9 Having trouble sorting them least to greatest and if the numerator is positive but the denominator is negative switch both so that the numerator is negative and the denominator positive
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started