Question

Lab 1.java only Goal: This lab will give you experience with defining and using classes and...

Lab 1.java only

Goal: This lab will give you experience with defining and using classes and fields, and with conditionals and recursive functions. Getting Started --------------- Read the Fraction.java class into a text editor and compile it filling in the command javac -g Fraction.java. The program should compile without errors. In a shell window, run the program using "java Fraction". The program should run, although it will print fractions in a non-reduced form, like 12/20. Part I: Constructors (1 point) ------------------------------- Look at the main method in the Fraction class, which declares and constructs four Fraction objects. Four different constructors are used, each with different parameters. Fraction f0 = new Fraction(); Fraction f1 = new Fraction(3); Fraction f2 = new Fraction(12, 20); Fraction f3 = new Fraction(f2); Look at the implementations of the constructors. The two-parameter constructor is straightforward. It assigns the parameters to the numerator and denominator fields. The constructor with one int parameter uses some new syntax: this(n, 1); The effect of this statement is to call the two-parameter constructor, passing n and 1 as parameters. "this" is a keyword in Java, which normally refers to the object on which a method is invoked. In a constructor, it can be used (as above) to invoke a constructor from within another constructor. We could have written the one-parameter constructor thusly: public Fraction(int n) { if (n < 0) { System.out.println("Fatal error: Negative numerator."); System.exit(0); } numberOfFractions++; numerator = n; denominator = 1; } Why call the two-parameter constructor instead? The reason is one of good software engineering: by having three of the constructors call the fourth, we have reduced duplicate code--namely, the error-checking code and fraction counting code in the first constructor. By reusing code this way, the program is shorter, and more importantly, if we later find a bug in the constructor, we might only need to fix the first constructor to fix all of them. This principle applies to methods in general, not just constructors. In your own programs, if you find yourself copying multiple lines of code for reuse, it is usually wise to put the common code into a new shared method. The no-parameter constructor does not use the good style just described. Modify it to call the two-parameter constructor. Then, fill in the fourth constructor so that it uses the good style and correctly duplicates the input Fraction (it does neither now). Part II: Using Objects (1 point) --------------------------------- Further on in the main method, there are four lines commented out. Remove the comment markers and fill in the two missing expressions so that sumOfTwo is the sum of f1 and f2, and sumOfThree is the sum of f0, f1, and f2. Part III: Defining Classes (1 point) ------------------------------------- The changeNumerator and fracs methods don’t work. Fix them. You may NOT change their signatures. Each fix should require the addition of just one word. These changes may or may not be in the methods themselves. Part IV: Conditionals and Recursive Functions (1 point) -------------------------------------------------------- The main method prints the Fractions thusly: System.out.println("The fraction f0 is " + f0.toString()); System.out.println("The fraction f1 is " + f1); // toString is implicit System.out.println("The fraction f2 is " + f2); System.out.println("The fraction f3 is " + f3 + ", which should equal f2"); How does Java know what to do when printing the fractions f1, f2, and f3? In the case of f0, we have invoked the toString method; please read the toString() code. In the next three lines, we are asking Java to concatenate a Fraction to the end of a String. A Fraction is not a String, so can’t be concatenated directly, but Java cleverly looks for a method called toString to convert each Fraction to a string. This is standard in Java: any object can have a toString method, and if it does, that method will be automatically called when you concatenate the object to a String. (Actually, _every_ object has a toString method, but the default toString isn’t particularly enlightening.) As we noted earlier, the toString method prints a Fraction in non-reduced form. Examine the code in the toString method. It is calling another method called gcd that computes the greatest common divisor (GCD) of two positive integers. If this method worked correctly, toString would print Fractions in reduced form; instead, gcd always returns 1. Rewrite the body of gcd so that it is a recursive function that correctly computes the GCD. Recompile and run your program. Here is pseudocode for a recursive GCD function. a and b must be nonnegative. function gcd(a, b) if b = 0 return a else return gcd(b, a mod b)

Check-off
---------
1 point: Run your program to demonstrate that f2 and f3 are initially equal.
1 point: Demonstrate that your program correctly computes the two sums of
fractions.
1 point: Demonstrate that your program changes f3 to 7/20, and prints the
correct number of Fraction objects.
1 point: Demonstrate your program that correctly computes GCDs and fractions
in reduced form.

........................................................................................................///////////.

/* Fraction.java */
  
import java.io.*;

/** The Fraction class implements nonnegative fractions (rational numbers).
*/
class Fraction {

/* private fields within a Fraction. */
private int numberOfFractions = 0;

private int numerator;
private int denominator;

/** Constructs a Fraction n/d.
* @param n is the numerator. Must be nonnegative.
* @param d is the denominator. Must be positive.
*/
public Fraction(int n, int d) {
if (n < 0) {
System.out.println("Fatal error: Negative numerator.");
System.exit(0);
}
if (d < 1) {
System.out.println("Fatal error: Nonpositive denominator.");
System.exit(0);
}
numberOfFractions++;
numerator = n;
denominator = d;
}

/** Constructs a Fraction n/1.
* @param n is the numerator. Must be nonnegative.
*/
public Fraction(int n) {
this(n, 1);
}

/** Constructs a Fraction 0/1.
*/
public Fraction() {
numberOfFractions++;
numerator = 0;
denominator = 1;
}

/** Copies the Fraction "original".
*/
public Fraction(Fraction original) {
numberOfFractions++;
numerator = 0;
denominator = 1;
}

/** Converts this Fraction to a string format: "numerator/denominator."
* Fractions should be printed in reduced form (part of your assignment is
* to make this true).
* @return a String representation of this Fraction.
*/
public String toString() {
int thisGcd = gcd(numerator, denominator);

return (numerator / thisGcd + "/" + denominator / thisGcd);
}

/** Return the sum of two fractions.
* @param f2 is the Fraction to be added.
* @return the result of adding f2 to this Fraction.
*/
public Fraction add(Fraction f2) {
Fraction r = new Fraction((numerator * f2.denominator) +
           (f2.numerator * denominator),
           denominator * f2.denominator);
return r;
}

/** Replaces this Fraction's numerator with a new value.
* @param numerator is the new numerator. Must be nonnegative.
*/
public void changeNumerator(int numerator) { // DO NOT CHANGE THIS SIGNATURE!
// Fix the bug that prevents this method from working correctly.
if (numerator < 0) {
System.out.println("Fatal error: Negative numerator.");
System.exit(0);
}
numerator = numerator;
}

/** Returns the number of Fraction objects in existence.
* @return the number of Fraction objects in existence.
*/
public int fracs() { // DO NOT CHANGE THIS SIGNATURE!
// Fix the bug that prevents this method from working correctly.
return numberOfFractions;
}

/** Computes the greatest common divisor (gcd) of the two inputs.
* @param x must be nonnegative
* @param y must be nonnegative
* @return the gcd of x and y
*/
static private int gcd(int x, int y) {
/* Replace the following line with your solution. */
return 1;
}

/** Put the Fraction class through some tests.
* @param argv is not used.
*/
public static void main(String[] argv) {

/* Test all four contructors and toString. */
Fraction f0 = new Fraction();
Fraction f1 = new Fraction(3);
Fraction f2 = new Fraction(12, 20);
Fraction f3 = new Fraction(f2);

System.out.println("\nTesting constructors and toString():");
System.out.println("The fraction f0 is " + f0.toString());
System.out.println("The fraction f1 is " + f1); // toString is implicit.
System.out.println("The fraction f2 is " + f2);
System.out.println("The fraction f3 is " + f3 + ", which should equal f2");

/* Test the add method. */
System.out.println("\nTesting add:");

/*
Fraction sumOfTwo = _______________; // Sum of f1 and f2.
Fraction sumOfThree = ______________; // Sum of f0, f1, and f2.

System.out.println("The sum of " + f1 + " and " + f2 + " is " + sumOfTwo);
System.out.println("The sum of " + f0 + ", " + f1 + " and " + f2 + " is " +
sumOfThree);
*/

/* Test the methods used in Part III. */
System.out.println("\nTesting changeNumerator and fracs:");

f3.changeNumerator(7);
System.out.println("Now f3 is " + f3 + ", which should be 7/20");
System.out.println("The total number of Fraction objects is " +
f3.fracs());

/* Test gcd function (static method). */
System.out.println("\nTesting gcd:");
System.out.println("The gcd of 2 and 10 is: " + gcd(2, 10));
System.out.println("The gcd of 15 and 5 is: " + gcd(15, 5));
System.out.println("The gcd of 24 and 18 is: " + gcd(24, 18));
System.out.println("The gcd of 10 and 10 is: " + gcd(10, 10));
System.out.println("The gcd of 21 and 400 is: " + gcd(21, 400));
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Fraction.java

import java.io.*;

/** The Fraction class implements nonnegative fractions (rational numbers).

*/

public class Fraction {

      

       /* private fields within a Fraction. */

       private static int numberOfFractions = 0; // make it static so that one copy of field is shared by all the objects of Fraction class

       private int numerator;

       private int denominator;

      

       /** Constructs a Fraction n/d.

       * @param n is the numerator. Must be nonnegative.

       * @param d is the denominator. Must be positive.

       */

       public Fraction(int n, int d) {

             if (n < 0) {

                    System.out.println("Fatal error: Negative numerator.");

                    System.exit(0);

             }

             if (d < 1) {

                    System.out.println("Fatal error: Nonpositive denominator.");

                    System.exit(0);

             }

             numberOfFractions++;

             numerator = n;

             denominator = d;

       }

      

       /** Constructs a Fraction n/1.

       * @param n is the numerator. Must be nonnegative.

       */

       public Fraction(int n) {

             this(n, 1);

       }

      

       /** Constructs a Fraction 0/1.

       */

       public Fraction() {

             this(0,1);

       }

      

       /** Copies the Fraction "original".

       */

       public Fraction(Fraction original) {

             this(original.numerator,original.denominator);

       }

      

       /** Converts this Fraction to a string format: "numerator/denominator."

       * Fractions should be printed in reduced form (part of your assignment is

       * to make this true).

       * @return a String representation of this Fraction.

       */

       public String toString() {

       int thisGcd = gcd(numerator, denominator);

       return (numerator / thisGcd + "/" + denominator / thisGcd);

       }

       /** Return the sum of two fractions.

       * @param f2 is the Fraction to be added.

       * @return the result of adding f2 to this Fraction.

       */

       public Fraction add(Fraction f2) {

       Fraction r = new Fraction((numerator * f2.denominator) +

                  (f2.numerator * denominator),

                  denominator * f2.denominator);

       return r;

       }

       /** Replaces this Fraction's numerator with a new value.

       * @param numerator is the new numerator. Must be nonnegative.

       */

       public void changeNumerator(int numerator) { // DO NOT CHANGE THIS SIGNATURE!

       // Fix the bug that prevents this method from working correctly.

             if (numerator < 0) {

                    System.out.println("Fatal error: Negative numerator.");

                    System.exit(0);

             }

             this.numerator = numerator;

       }

      

       /** Returns the number of Fraction objects in existence.

       * @return the number of Fraction objects in existence.

       */

       public int fracs() { // DO NOT CHANGE THIS SIGNATURE!

       // Fix the bug that prevents this method from working correctly.

       return numberOfFractions;

       }

       /** Computes the greatest common divisor (gcd) of the two inputs.

       * @param x must be nonnegative

       * @param y must be nonnegative

       * @return the gcd of x and y

       */

       static private int gcd(int x, int y) {

       /* Replace the following line with your solution. */

             if(x >= 0 && y >= 0)

             {

                    if(y == 0)

                           return x;

                    return (gcd(y,x%y));

             }

             return 1;

       }

      

       /** Put the Fraction class through some tests.

       * @param argv is not used.

       */

      

       public static void main(String[] args) {

             /* Test all four contructors and toString. */

             Fraction f0 = new Fraction();

             Fraction f1 = new Fraction(3);

             Fraction f2 = new Fraction(12, 20);

             Fraction f3 = new Fraction(f2);

             System.out.println("\nTesting constructors and toString():");

             System.out.println("The fraction f0 is " + f0.toString());

             System.out.println("The fraction f1 is " + f1); // toString is implicit.

             System.out.println("The fraction f2 is " + f2);

             System.out.println("The fraction f3 is " + f3 + ", which should equal f2");

             /* Test the add method. */

             System.out.println("\nTesting add:");

            

             Fraction sumOfTwo = f1.add(f2); // Sum of f1 and f2.

             Fraction sumOfThree = f0.add(f1).add(f2); // Sum of f0, f1, and f2.

             System.out.println("The sum of " + f1 + " and " + f2 + " is " + sumOfTwo);

             System.out.println("The sum of " + f0 + ", " + f1 + " and " + f2 + " is " +

             sumOfThree);

            

             /* Test the methods used in Part III. */

             System.out.println("\nTesting changeNumerator and fracs:");

             f3.changeNumerator(7);

             System.out.println("Now f3 is " + f3 + ", which should be 7/20");

             System.out.println("The total number of Fraction objects is " +

             f3.fracs());

             /* Test gcd function (static method). */

             System.out.println("\nTesting gcd:");

             System.out.println("The gcd of 2 and 10 is: " + gcd(2, 10));

             System.out.println("The gcd of 15 and 5 is: " + gcd(15, 5));

             System.out.println("The gcd of 24 and 18 is: " + gcd(24, 18));

             System.out.println("The gcd of 10 and 10 is: " + gcd(10, 10));

             System.out.println("The gcd of 21 and 400 is: " + gcd(21, 400));

       }

}

//end of Fraction.java

Output:

Testing constructors and toString(): The fraction fo is 0/1 The fraction f1 is 3/1 The fraction f2 is 3/5 The fraction f3 is

Add a comment
Know the answer?
Add Answer to:
Lab 1.java only Goal: This lab will give you experience with defining and using classes and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with the following Java code Consider a class Fraction of fractions. Each fraction...

    I need help with the following Java code Consider a class Fraction of fractions. Each fraction is signed and has a numerator and a denominator that are integers. Your class should be able to add, subtract, multiply, and divide two fractions. These methods should have a fraction as a parameter and should return the result of the operation as a fraction. The class should also be able to find the reciprocal of a fraction, compare two fractions, decide whether two...

  • When we test your Fraction.java we will use the given FractionTester.java file. Your Fraction.java file -MUST-...

    When we test your Fraction.java we will use the given FractionTester.java file. Your Fraction.java file -MUST- work perfectly with the supplied FractionTester.java file. You may NOT modify the FractionTester to make your Fraction class work right. Starter Fraction File: Fraction.java ADD METHODS TO THIS FILE. HAND IN THIS FILE ONLY. Given/Completed Tester File: FractionTester.java DO NOT MODIFY. DO NOT HAND IN. You are to add the following methods to the given Fraction.java file public Fraction add( Fraction other) returns a...

  • java only no c++ Write a Fraction class whose objects will represent fractions. You should provide...

    java only no c++ Write a Fraction class whose objects will represent fractions. You should provide the following class methods: Two constructors, a parameter-less constructor that assigns the value 0 to the Fraction, and a constructor that takes two parameters. The first parameter will represent the initial numerator of the Fraction, and the second parameter will represent the initial denominator of the Fraction. Arithmetic operations that add, subtract, multiply, and divide Fractions. These should be implemented as value returning methods...

  • Need help with Java for Fraction exercise

    Add another public method called add to your Fraction class. This method adds another fraction to the ‘calling object’. Thus, the method will take a Fraction class object as a parameter, add this parameter fraction to the calling object (fraction), and return a Fraction object as a result. HINT: We can use cross multiplication to determine the numerator of the resultant Fraction. The denominator of the resultant Fraction is simply the multiplication of the denominators of the two other Fractions.Add...

  • I have provided a main method. Please add your fraction class. You need constructors, add, subtract,...

    I have provided a main method. Please add your fraction class. You need constructors, add, subtract, multiply, and divide methods, and a toString method. Your toString method needs to return the numerator followed by / followed by the denominator - NO spaces. DO NOT make any attempt to reduce the fractions (we shall do that later). Please add comments throughout. import java.util.Scanner; public class H4 { public static class Fraction { } public static void main(String[] args) { Fraction f=...

  • Hello, I'm looking to modify my fraction program to include constructors and destructors. Here are all...

    Hello, I'm looking to modify my fraction program to include constructors and destructors. Here are all the instructions: Create constructors default two argument three argument copy constructor Create a destructor. The destructor should set whole and numerator to zero and denominator to one. Add cout statements to the constructors and the destructor so you know when it's getting executed. Add system ("pause") to the destructor so you know when it executes. Only positive values allowed If denominator is 0 set...

  • Do the following: 1) Add a constructor with two parameters, one for the numerator, one for...

    Do the following: 1) Add a constructor with two parameters, one for the numerator, one for the denominator. If the parameter for the denominator is 0, set the denominator to 1 2) Add a function that overloads the < operator 3) Add a function that overloads the * operator 4) Modify the operator<< function so that if the numerator is equal to the denominator it just prints 1 5) Modify the operator>> function so that after it reads the denominator...

  • Please use C++ and add comments to make it easier to read. Do the following: 1)...

    Please use C++ and add comments to make it easier to read. Do the following: 1) Add a constructor with two parameters, one for the numerator, one for the denominator. If the parameter for the denominator is 0, set the denominator to 1 2) Add a function that overloads the < operator 3) Add a function that overloads the * operator 4) Modify the operator<< function so that if the numerator is equal to the denominator it just prints 1...

  • In C++ Fix any errors you had with HW5(Fraction class). Implement a function(s) to help with...

    In C++ Fix any errors you had with HW5(Fraction class). Implement a function(s) to help with Fraction addition. \**************Homework 5 code*****************************/ #include<iostream> using namespace std; class Fraction { private: int wholeNumber, numerator, denominator;    public: //get methods int getWholeNumber() { return wholeNumber; } int getNumerator() { return numerator; } int getDenominator() { return denominator; } Fraction()// default constructor { int w,n,d; cout<<"\nEnter whole number : "; cin>>w; cout<<"\nEnter numerator : "; cin>>n; cout<<"\nEnter denominator : "; cin>>d; while(d == 0)...

  • C++ CODE /* This is program project 2 on page 695. * Before you begin the...

    C++ CODE /* This is program project 2 on page 695. * Before you begin the project, please read the project description * on page 695 first. * * Author: Your Name * Version: Dates */ #include <iostream> #include <cmath> #include <cassert> using namespace std; class Fraction { public: // constructor Fraction(int a, int b); // generate a fraction which is a/b Fraction(int a); // generate a fraction which is a/1 Fraction(); // generate a fraction which is 0/1. i.e...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT