Question

In: Computer Science

Given the main method of a driver class, write a Fraction class. Include the following instance...

Given the main method of a driver class, write a Fraction class. Include the following instance methods:

add,

multiply,

print,

printAsDouble,

and a separate accessor method for each instance variable.

    1. Write a Fraction class that implements these methods:
  • add ─ This method receives a Fraction parameter and adds the parameter fraction to the calling object fraction.
  • multiply ─ This method receives a Fraction parameter and multiplies the parameter fraction by the calling object fraction.
  • print ─ This method prints the fraction using fraction notation (1/4, 21/14, etc.)
  • printAsDouble ─ This method prints the fraction as a double (0.25, 1.5, etc.)

Separate accessor methods for each instance variable in the Fraction class.

Provide a driver class, FractionDemo,   that demonstrates this Fraction class. The driver class should contain this main method:

public static void main(String[] args)

{

Scanner stdIn = new Scanner(System.in);

Fraction c, d, x;       // Fraction objects

System.out.println("Enter numerator; then denominator.");

c = new Fraction(stdIn.nextInt(), stdIn.nextInt());

c.print();

System.out.println("Enter numerator; then denominator.");

d = new Fraction(stdIn.nextInt(), stdIn.nextInt());

d.print();

x = new Fraction();     // create a fraction for number 0

System.out.println("Sum:");

x.add(c).add(d);

x.print();

x.printAsDouble();

x = new Fraction(1, 1); // create a fraction for number 1

System.out.println("Product:");

x.multiply(c).multiply(d);

x.print();

x.printAsDouble();

System.out.println("Enter numerator; then denominator.");

x = new Fraction(stdIn.nextInt(), stdIn.nextInt());

x.printAsDouble();

} // end main

Note that this demonstration driver does not call the accessor methods. That’s OK.   Accessor methods are often implemented regardless of whether there’s an immediate need for them. That’s because they are very useful methods in general and providing them means that future code can use them when the need arises.

Sample session:

Enter numerator; then denominator.

5

8

5/8

Enter numerator; then denominator.

4

10

4/10

Sum:

82/80

1.025

Product:

20/80

0.25

Enter numerator; then denominator.

6

0

infinity

  1. Modify the code so that it can handle negative numerators and negative denominators, and provide a helping method that performs fraction reduction.

Sample session using negative numbers and reduction:

Enter numerator; then denominator.

-5

-8

5/8

Enter numerator; then denominator.

4

-10

-2/5

Sum:

9/40

0.225

Product:

-1/4

-0.25

Enter numerator; then denominator.

0

-0

indeterminate

Solutions

Expert Solution

Fraction.java

public class Fraction {
   private int numerator;
   private int denominator;
  
   Fraction(){
       numerator = 0;
       denominator = 1;
   }
   Fraction(int n, int d){
       //If both numerator and denominator are negative
       if(n<0 && d<0) {
           this.numerator = -n;
           this.denominator = -d;
       }
       //If numerator is positive, denominator is negative
       else if (n>0 && d<0){
           numerator = -n;
           denominator = -d;
       }
       //Otherwise
       else {
           numerator = n;
           denominator = d;
       }
   }
  
   public int getNumerator() {
       return numerator;
   }
   public int getDenominator() {
       return denominator;
   }
        //Adds Fraction f to the current Fraction object, and returns new Fraction
   public Fraction add(Fraction f) {
       int num = this.numerator*f.denominator + this.denominator*f.numerator;
       int denom = this.denominator*f.denominator;
       this.numerator = num;
       this.denominator = denom;
       return this;
   }
   //Multiplies Fraction f to the current Fraction object, and returns new Fraction
   public Fraction multiply(Fraction f) {
       int num = this.numerator * f.numerator;
       int denom = this.denominator * f.denominator;
       this.numerator = num;
       this.denominator = denom;
       return this;
   }
      
   public void print() {
       if(numerator == 0 && denominator == 0)
           System.out.println("Indeterminate");
       else if (denominator==0)
           System.out.println("Infinity");
       else
           System.out.println(numerator + "/" + denominator);
   }
  
   public void printAsDouble() {
       System.out.println((double)numerator/denominator);
   }
}

FractioDemo.java

import java.util.Scanner;

public class FractionDemo {

   public static void main(String[] args) {
       Scanner stdIn = new Scanner(System.in);
       Fraction c, d, x;       // Fraction objects
       System.out.println("Enter numerator; then denominator.");
       c = new Fraction(stdIn.nextInt(), stdIn.nextInt());
       c.print();
       System.out.println("Enter numerator; then denominator.");
       d = new Fraction(stdIn.nextInt(), stdIn.nextInt());
       d.print();
       x = new Fraction();     // create a fraction for number 0
       System.out.println("Sum:");
       x.add(c).add(d);
       x.print();
       x.printAsDouble();
      
       x = new Fraction(1, 1); // create a fraction for number 1
       System.out.println("Product:");
       x.multiply(c).multiply(d);
       x.print();
       x.printAsDouble();
       System.out.println("Enter numerator; then denominator.");
       x = new Fraction(stdIn.nextInt(), stdIn.nextInt());
       x.printAsDouble();      
   }

}


Related Solutions

3. [Method 1] In the Main class, write a static void method to print the following...
3. [Method 1] In the Main class, write a static void method to print the following text by making use of a loop. Solutions without a loop will receive no credit. 1: All work and no play makes Jack a dull boy. 2: All work and no play makes Jack a dull boy. 3: All work and no play makes Jack a dull boy. 4: All work and no play makes Jack a dull boy. 4. [Method 2] In the...
Java Program to write a Fraction class that models a mathematical fraction. The fraction class needs...
Java Program to write a Fraction class that models a mathematical fraction. The fraction class needs to support simple arithmetic functions including taking the sum, difference, and the product of the division of the two. Do not include a main() method in the Fraction class. The Fraction class will implement the following class methods: Fraction add (Fraction f1, Fraction f2); // f1 + f2 and returns a new Fraction Fraction sub (Fraction f1, Fraction f2); // f1 - f2 and...
IN JAVA: Build a class called ExamPractice from scratch. This class should include a main method...
IN JAVA: Build a class called ExamPractice from scratch. This class should include a main method that does the following: Prompt the user to enter a number of inches Read the number of inches entered from the console Convert the inches into an equivalent number of miles, yards, feet, and inches. Output the results to the console. For example, if a user entered 100000 inches, the program would output: 100000 inches is equivalent to: Miles: 1 Yards: 1017 Feet: 2...
For python Write a new method for the Fraction class called mixed() which returns a string...
For python Write a new method for the Fraction class called mixed() which returns a string that writes out the Fraction in mixed number form. Here are some examples: f1 = Fraction(1, 2) print(f1.mixed()) # should print "1/2" f2 = Fraction(3, 2) print(f2.mixed()) # should return "1 and 1/2" f3 = Fraction(5, 1) print(f3.mixed()) # should return "5" def gcd(m, n): while m % n != 0: oldm = m oldn = n m = oldn n = oldm %...
Write a method speedingTicket() that decides whether a driver should be given a ticket from a...
Write a method speedingTicket() that decides whether a driver should be given a ticket from a police officer. The method accepts three parameters: speed (i.e., car speed) as integer; limit (i.e., speed limit) as integer and a boolean named donut indicating whether or not the police officer has eaten a donut today. A police officer that has eaten a donut is happy, so he/she is less likely to give the driver a ticket. Your method should display either “Give Ticket”...
Name the project pa3 [Method 1] In the Main class, write a static void method to...
Name the project pa3 [Method 1] In the Main class, write a static void method to print the following text by making use of a loop. Solutions without a loop will receive no credit. 1: All work and no play makes Jack a dull boy. 2: All work and no play makes Jack a dull boy. 3: All work and no play makes Jack a dull boy. 4: All work and no play makes Jack a dull boy. [Method 2]...
Question - Write a Client class with a main method that tests the data structures as...
Question - Write a Client class with a main method that tests the data structures as follows: For the ArrayStack, LinkedStack, ArrayQueue, LinkedQueue, and ArrayList: Perform a timing test for each of these data structures. Each timing test should measure in nanoseconds how long it takes to add and remove N Integers from the structure. N should vary from 10 to 1,000,000,000 increasing N by a factor of 10 for each test. Depending on your system you may run out...
Add the following method below to the CardDeck class, and create a test driver to show...
Add the following method below to the CardDeck class, and create a test driver to show that they work correctly. int cardsRemaining() //returns a count of the number of undealt cards remaining in the deck. Complete in Java programming language. // Models a deck of cards. Includes shuffling and dealing. //---------------------------------------------------------------------- package Homework4; import java.util.Random; import java.util.Iterator; import javax.swing.ImageIcon; public class CardDeck { public static final int NUMCARDS = 52; protected ABList<Card> deck; protected Iterator<Card> deal; public CardDeck() { deck...
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of...
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of Poem objects, read in the information from PoemInfo.txt and create Poem objects to populate the ArrayList. After all data from the file is read in and the Poem objects added to the ArrayList- print the contents of the ArrayList. Paste your PoemDriver.java text (CtrlC to copy, CtrlV to paste) into the open space before. You should not change Poem.java or PoemInfo.txt. Watch your time...
#Write a class called "Burrito". A Burrito should have the #following attributes (instance variables): # #...
#Write a class called "Burrito". A Burrito should have the #following attributes (instance variables): # # - meat # - to_go # - rice # - beans # - extra_meat (default: False) # - guacamole (default: False) # - cheese (default: False) # - pico (default: False) # - corn (default: False) # #The constructor should let any of these attributes be #changed when the object is instantiated. The attributes #with a default value should be optional. Both positional #and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT