Question

Need help with Java for Fraction exercise

  1. 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.


  2. Add a private method simplify() to your Fraction class that converts a fraction to its simplest form. For example, the fraction 20 / 60 should be stored in the class instance variables as 1 / 3 (i.e. numerator = 1, denominator = 3). N.B. you will need a method to determine the Greatest Common Divisor (GCD). Remember, both of these methods (simplify and gcd) must be private. As these methods are private, client programs cannot access them. So, how are they to be used? Given their purpose, it would mean that any Fraction class method that modifies the instance variables (e.g.: add, ICT167 Principles of Computer Science 2 constructor, set) should call the simplify() method to reduce the instance variables to their minimum values. Thus, these methods are used only for housekeeping; they are not to be used by client programs. Make sure you understand how the following GCD algorithm work before implementing it.

                         // function gcd; two integer parameters

                            int gcd(int n1, int n2)

                                 // local variable c

                                 int c

                                loop while ( n1 != 0 AND n2 != 0 )

                                c = n2

                                n2 = n1 % n2 // modulus operator

                                n1 = c

                           return (n1 + n2)


  3. Write a client class (TestFraction2) that allows the user to add up any number of non-zero fractions. The program should display the running total as an exact fraction (in simplified form as numerator / denominator). The user can finish by entering a fraction that represents a zero fraction. Note: If you need any implement any more methods (private or public) in the class to complete this question, you will need to justify and explain it clearly here.



  4. import java.util.Scanner;
    
    public class Fraction 
    {
        private int numerator;
        private int denominator;
        public void inputValues()
        {
            System.out.println("Enter any 2 numbers for a fraction.");
            Scanner input = new Scanner(System.in);
            numerator = input.nextInt();
            denominator = input.nextInt();
        }
        
        public void outputValues()
        {
            System.out.println("The fraction is " + numerator + "/" + denominator + ":");
        }
        public int getNumerator()
        {
            return numerator;
        }
        public int getDenominator()
        {
            return denominator;
        }
    }
  5. import java.util.Scanner;
    
    /* import Fraction.java into this class and
    use while loop to continue asking the user to enter
    a fraction and if the user enter a negative input
    the loop will end
    */
    
    
    public class TestFraction 
    {
        public static void main(String[] args)
        {
            Scanner kboard = new Scanner(System.in);
            Fraction fTotal = new Fraction(); 
            fTotal.setNumerator(0); // Zero fraction number
            fTotal.setDenominator(1);
            Fraction fNumber = new Fraction();
            while (true)
            {
                System.out.println("Enter numerator: ");
                int numerator = kboard.nextInt();
                if (numerator == 0)
                {
                    break; // Zero fraction, stop the loop
                }
                System.out.println("Enter denominator: ");
                int denominator = kboard.nextInt();
                fNumber.setNumerator(numerator);
                fNumber.setDenominator(denominator);
                fTotal = fTotal.add(fNumber);
                System.out.println(fTotal.toString());
            }
        }
    }
0 0
Add a comment Improve this question Transcribed image text
Answer #1

1. 

TestFraction.java:

import java.util.Scanner;
public class TestFraction {
public static void main(String arg[]) {
Scanner in = new Scanner(System.in);
int numerator, denominator;
while (true) {
System.out.print("Enter a numerator : ");
numerator = in.nextInt();
if (numerator >= 0) {
System.out.print("Enter a denominator : ");
denominator = in.nextInt();
Fraction f = new Fraction(numerator, denominator);
System.out.println("Your fraction is: " + f);
System.out.println("---------------------");
System.out.println("Enter another number to compare");
System.out.print("Enter numerator: ");
int cpNumerator = in.nextInt();
System.out.print("Enter denomainator: ");
int cpDenominator = in.nextInt();
Fraction f1 = new Fraction(cpNumerator, cpDenominator);
if (f.isEquals(f1)) {
System.out.println("Both fractions " + f1 + " and " + f + " are equal\n");
} else {
System.out.println("Both fractions " + f1 + " and " + f + " are not equal\n");
}
} else {
System.out.println("exiting");
System.exit(0);
}
}
}
}


answered by: Zahidul Hossain
Add a comment
Know the answer?
Add Answer to:
Need help with Java for Fraction exercise
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 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=...

  • 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...

  • 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)...

  • C++ Fraction calculator Need help with code, cant use "using namespace std" Objectives Create and use...

    C++ Fraction calculator Need help with code, cant use "using namespace std" Objectives Create and use functions. Use a custom library and namespace. Use reference variables as parameters to return values from functions. Create a robust user interface with input error checking. Use exceptions to indicate errors. Resources kishio.h kishio.cpp Assignment requirements You will need eight methods (including main). One is given to you. Their requirements are specified below: menu: The menu function takes no arguments, but returns a char...

  • The following is the class definition for Multiplier. This class has five (5) members: two private...

    The following is the class definition for Multiplier. This class has five (5) members: two private instance variables two private methods one public method this is only public method for the class it calls other two private methods import java.util.*; //We need to use Scanner & Random in this package public class Multiplier {        private int answer; //for holding the correct answer        private Random randomNumbers = new Random(); //for creating random numbers        //ask the user to work...

  • Add on to the java code below to include a welcome message and menu for the...

    Add on to the java code below to include a welcome message and menu for the user. The user should be able to decide when to exit the program ( the user can enter his data included in code below ), and then can either exit, OR enter another one. Need a loop structure in this code. import java.util.Scanner; public class ReduceFraction { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Enter a numerator: "); int n...

  • I need help with a java error Question: Consider a graphics system that has classes for...

    I need help with a java error Question: Consider a graphics system that has classes for various figures—say, rectangles, boxes, triangles, circles, and so on. For example, a rectangle might have data members’ height, width, and center point, while a box and circle might have only a center point and an edge length or radius, respectively. In a well-designed system, these would be derived from a common class, Figure. You are to implement such a system. The class Figure is...

  • (Java with Netbeans) Programming. Please show modified programming code for already given Main class, and programming...

    (Java with Netbeans) Programming. Please show modified programming code for already given Main class, and programming for code for the new GameChanger class. // the code for Main class for step number 6 has already been given, please show modified progrraming for Main class and GameCHanger class, thank you. package .games; import java.util.Random; import java.util.Scanner; public class Main { public static void main(String args[]) { System.out.println("Welcome to the Number Guessing Game"); System.out.println(); Scanner sc = new Scanner(System.in); // Get upper...

  • I need to create a code for this prompt: In this project we will build a...

    I need to create a code for this prompt: In this project we will build a generic UserInput class for getting keyboard input from the user. Implementation: The class UserInput is a 'Methods only' class, and all the methods should be declared static. Look at the TestScanner.java program at the bottom of this page that inputs a string, int and double. It shows you how to use Scanner class to get input from the keyboard. Write FOUR simple methods, one...

  • 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)...

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