Create a new class called fraction

Assignment Help Software Engineering
Reference no: EM131560073

Application: Write a Fraction API

An API is an Application Programming Interface. It isn't a complete program. Instead, it is a set of classes, constructors, and interfaces that define objects and methods for other programmers to use. They can't run on their own; they are designed to show other programmers how to call and use the classes when these programmers write other "complete" programs.

In this Application, you are going to write an API for a Fractions class. It will accept fractions as input and perform various mathematical operations on them. But why would a programmer need an API for fractions?

Java provides the int data type for holding integers (whole numbers, with no decimal point), and double and float, to hold numbers with a decimal point (called floating point numbers). There is a difference between the mathematical concept of a real number and the way it is implemented as a floating point number in a programming language like Java. As mathematical concepts, double and float can have an infinite length; for instance, 1/3 is 0.333333... ad infinitum, 2/3 is .6666666666... ad infinitum, and pi is 3.14159... ad infinitum. Computers cannot allocate an infinite amount of storage for a number. At some point, depending on how much storage is assigned a float or double, the fraction will be rounded. 2/3 may be rounded to .66666667 due to storage allocation for the type. So how can 2/3 be represented in Java without a loss of precision?

The solution is to represent a fraction as the ratio of two integers, a numerator and a denominator. The fraction class will need to store these two values, and it must be able to add, subtract, multiply, and divide fractions. It will also need to test for equality between two fractions.

If the first fraction is represented as a/b, and the second as c/d, here are the formulae for calculating these operations:

Addition [a/b + c/d]: (a*d + b*c) / b*d Subtraction [a/b - c/d]: (a*d - b*c) / b*d Multiplication [a/b * c/d]: a*c / b*d Division [(a/b) / (c/d)]: a*d / b*c

Before you start programming, there are a few things you'll need to do:

- You will need the NetBeans IDE and the JUnit testing framework plugin. NetBeans is an Integrated Development Environment (IDE). IDEs are what programmers typically use to create programs. They contain many of the tools that aid in the development of software programs, all in one application. You may already have another IDE installed on your system, but you will be using NetBeans for this course.

JUnit4 is a testing framework for Java that supports Test-Driven Development. You will find JUnit helpful for testing as you create the Fractions API.

- Download and install NetBeans by performing the following steps:
o Go to https://www.oracle.com/technetwork/java/javase/downloads/index.html and click on the NetBeans button to download the NetBeans + JDK Bundle.
o Click the "Accept License Agreement" radio button, and then click on the Download link that corresponds to your operating system. Confirm the download by clicking OK or Run if a confirmation dialog box pops up.
o Install the NetBeans/JDK Bundle once it has finished downloading.

- Download and install the JUnit4 plugin for NetBeans by performing the following steps:
o Start NetBeans
o On the NetBeans start page, click the My NetBeans tab,

o Click Install Plugins, and then search for and install JUnit.

- If you are unfamiliar with NetBeans, step through the "Hello World" tutorial https://netbeans.org/kb/docs/java/quickstart.html on the basic use of NetBeans.

- When submitting your application, you will need to include screenshots of your application running. Since this application is an API and not a complete program, include screenshots of your usage of JUnit.

o To take a screenshot in the Windows operating system, press the Print Screen button (it may be necessary on certain keyboards to hold the fn key along with a print scr or prt sc button). Pressing this button saves the screenshot to the clipboard. To get it in a Word document, go to the document (or create a new Word document) and press Ctrl+V. Make sure to label each screenshot.

o In the Mac operating system, press Command+Shift+3 to take a screenshot of the entire screen. To take a screenshot of a particular area, press Command+Shift+4 and drag over the area you wish to shoot. The screenshot will be copied into the clipboard and saved on your desktop. To add the screenshot to a Word document, open or create the document, and then press Command+V to paste the screenshot into the document. Make sure to label each screenshot.

- If you're relatively new to programming in Java, or need a refresher, read chapters 2 and 3 of Murach's Java SE 6.

Programming

NetBeans organizes Java programs as Projects. These projects are where you'll write your program, and they contain all the classes, library references, and code necessary to run the program. Create a new project called Fractions. Within Fractions, create a new class called Fraction. NetBeans will supply a main method; delete this method, as you will be writing an API, not a complete program.

Before performing any operations on two fractions, you should first put them in lowest terms. For this you will also need to compute the greatest common divisor (GCD) of the numerator and denominator and then divide both by the GCD. You can compute the GCD of two numbers by using Euclid's Algorithm. If you're not familiar with this algorithm, there are a number of good definitions available on the web. (You'll find that searching the web for definitions, code snippets, and best practices is an invaluable tool for any programmer.) A Java implementation of Euclid's Algorithm is included as the gcd method below.

In your Fraction class, define two private int fields; these will hold the numerator and denominator of a fraction.

Define four static methods, named add, subtract, multiply, and divide. Each of these methods should be defined to take two Fraction arguments and return a new Fraction. For now, though, each of these methods should return null.

Define a constructor that takes two int parameters, corresponding to the numerator and denominator of a fraction. For now, the constructor should do nothing with these parameters; the constructor body should be empty. You may think this odd, but the reasons will be explained shortly.

Define one more static method to compute the greatest common divisor and name it gcd. The method should take two int parameters and return an int result. A Java implementation of gcd that uses Euclid's Algorithm is provided when you get to the testing portion of this assignment.

public boolean equals(Object o) { ... }

It should initially return false.

Add "doc" comments to each of the methods above. As you may recall, a documentation (doc) comment is a comment placed immediately before a class or method, to provide information to a programmer who wants to use these methods. (Other kinds of documentation, such as how to use the program or the details of how the method does its job, do not belong here.) In NetBeans, choose Tools → Analyze Javadoc, check all relevant checkboxes, and click Fix Selected; this will write skeleton doc comments for you, but you still have to fill in words to tell what each method does, what parameters it expects, and what it returns.

The JUnit Testing Framework
Except for the fully-coded gcd method, the methods you've just defined are essentially "stubs"; they provide a framework for the method and show what the input and output will be, but they don't perform the actual computations. At this point, it makes sense to provide a brief explanation of why you should first write method "stubs" that do nothing, or worse, return the wrong answer. It is a generally accepted truism that you should decide what a method is supposed to do before you write the method. When you have a plan, it is much easier to figure out where you are going or what you need to do. Many developers find it effective to write the tests for the methods before they write the actual code. This approach, called Test-Driven Development (TDD), turns out to have a number of benefits, including the following:
- TDD encourages the user of smaller, easily tested methods
- Errors are caught sooner and are more easily localized
- Long and painful debugging sessions are largely eliminated
- The tests actually get written, and are available for future use

JUnit is a testing framework that provides you with the ability to perform Test-Driven Development within NetBeans. With JUnit, you can have NetBeans create your test

methods for you. Since NetBeans doesn't know what your methods are supposed to do, the test methods it creates will also be stubs; you need to fill in the actual test code.

To install the JUnit plug-in, select your Fraction class in NetBeans, and then go to File > New File... > JUnit > Test for Existing Class. Click Next >, and then enter the name fraction.Fraction in the Class Name: box. Click Finish, choose JUnit 4.x, and then click Select. If you have done this correctly, you will see that NetBeans has written a FractionTest class for you, with several test method stubs.

Run the tests by choosing Run > Test Project (Fraction). You will get an easy-to-read display showing that all your tests failed, as they should have since you haven't written the code yet. Notice that double-clicking on an error message will move the cursor to the failed test.

Since the TDD process requires you to navigate frequently between the code and testing, you may want to adjust NetBeans to show them side by side. To see both Fraction and FractionTest at the same time, click and hold on either of those tabs and drag it to the right or left side of the edit window.

You will find it helpful to create a version of toString for the Fraction class. This will allow failed JUnit tests to print your fractions in a readable format. Here is an example:

@Override
public String toString() {
return numerator + "/" + denominator;
}

Creating and testing the methods in the Fraction Class
Usually it's best to work on one method at a time, starting with the methods that don't depend on other methods. Sometimes that's a bit tricky. In this case, if you don't have a

proper constructor, you have no fractions to test; and if you don't have a working equals method, you can't test that your results are correct. As a result, you should start by going back and forth between the two.

To develop each method, follow this procedure:
1. Fill in the test stub for the method with some actual tests.
2. Run the tests and make sure your new test code fails.
3. Fill in the method stub with actual code to do the work.
4. Run the tests and make sure the new test passes (if not, debug and repeat).
5. If the method should do more, return to step 1 to add more tests.

The following procedure steps you through this test-code-test-code sequence for the equals method. Afterward, you'll use this same sequence for developing the other methods.

For the equals method, three cases need to be tested.
- Case 1 is when two fractions are identical and the equals method should say they are equal.
- Case 2 is when two fractions are completely different and the equals
method should say they are unequal.
- Case 3 is when two fractions are equal but one or both aren't in lowest terms and appear to be different at first glance.

Case 1

In the testEquals method, replace the body (all eight lines) with the following:

assertEquals(new Fraction(1, 2), new Fraction(1, 2));

Now run the tests. All of them should fail, but for now just pay attention to testEquals. It should fail, because you defined an equals method that always returns false.

Next, fill in code for the equals test. It should cast the argument to a Fraction; then test that the two numerators are equal and the two denominators are equal. Run the tests again. This time, testFraction should pass. (If it doesn't, debug your code and try again.)

Case 2

Add the following line to testEquals:

assertFalse(new Fraction(1, 2).equals(new Fraction(1, 4)));

Run the test again. It does not pass because the default (empty) constructor just sets both the numerator and the denominator to zero. Fix the constructor to save its parameters, and run the tests again; this time testEquals should pass.

Case 3

Add the following line to testEquals:

assertEquals(new Fraction(1, 2), new Fraction(2, 4));

This really should pass because 1/2 = 2/4, but it doesn't. The best way to fix this is to keep all fractions in lowest terms, so that when you call new Fraction(2, 4), it is really saved as 1/2, not as 2/4.

To reduce a fraction to the lowest terms, divide both the numerator and the denominator by their greatest common divisor. Use the gcd method above for testing.

In the testGcd method, add one or more statements such as:

assertEquals(5, Fraction.gcd(15, 25));

Now use this Java implementation of the gcd method in your Fraction
constructor:

static int gcd(int a, int b) { a = Math.abs(a);
b = Math.abs(b); while (a != b) {
if (a > b) a = a - b; else b = b - a;
}
return a;
}

Although the gcd method has been provided for you, writing tests will help ensure that you understand what the method does.

Follow the test-code-test-code sequence for the add, subtract, multiply, and divide methods. Take a look at the formulae above for help implementing these methods.

You should also think about whether your code works for negative fractions.

As you can see, the TDD approach involves a lot of going back and forth between the test cases and the code being tested, never spending more than a few minutes in each. This may seem strange at first, but you will find that TDD practically guarantees you will make steady progress, finish your programs, and get them largely correct, because you will rarely if ever have to look through large amounts of code to find a bug.

If you would like to learn more of JUnit's features, NetBeans includes extensive tutorials. For a briefer introduction, see "Charlie's super short JUnit 4 tips."

Include screenshots of your program running as part of your submission. Provide screenshots showing test runs for each of the three cases. Then provide one screenshot showing the final run of the API. Show screenshots of your program being tested with JUnit.

Reference no: EM131560073

Questions Cloud

Finding a good sample of individuals : A company makes men's button-up dress shirts and is considering changes to its design. How might the company go about finding a good sample of individuals?
What is the relative frequency of adults : What is the relative frequency of adults in the sample who p efer to obtain their information through newspapers?
What makes this person a servant leader : Conduct independent research on this individual and create a profile of this leader.What makes this person a servant leader?
Find a third-degree polynomial function for the data : MODELING WITH DATA A hedge fund is a lightly regulated pool of professionally managed money. The assets (in billions of dollars) of hedge funds.
Create a new class called fraction : create a new class called Fraction. NetBeans will supply a main method; delete this method, as you will be writing an API, not a complete program.
Research and describe a historical event : Describe a scenario in which the system of checks and balances might work to prevent something that might cause harm to the American people.
What is carsons tax liability for the year : What is Carson's tax liability for the year in each of the following alternative circumstances
Estimate the number of people enrolled in hmos : MODELING WITH DATA The number of people (in millions) enrolled in HMOs from 1994 through 2002 is given in the following table.
How the court did or should resolve your example : Describe the events, the law, and how the court did or should resolve your example. What sources of law would have created or solved the problem you described?

Reviews

len1560073

7/10/2017 8:06:51 AM

How long it takes to get the answer Include screenshots of your program running as part of your submission. Provide screenshots showing test runs for each of the three cases. Then provide one screenshot showing the final run of the API. Show screenshots of your program being tested with JUnit. If you would like to learn more of JUnit's features, NetBeans includes extensive tutorials. For a briefer introduction, see "Charlie's super short JUnit 4 tips."

Write a Review

Software Engineering Questions & Answers

  Research report on software design

Write a Research Report on software design and answer diffrent type of questions related to design. Report contain diffrent basic questions related to software design.

  A case study in c to java conversion and extensibility

A Case Study in C to Java Conversion and Extensibility

  Create a structural model

Structural modeling is a different view of the same system that you analyzed from a functional perspective. This model shows how data is organized within the system.

  Write an report on a significant software security

Write an report on a significant software security

  Development of a small software system

Analysis, design and development of a small software system.

  Systems analysis and design requirements

Systems Analysis and Design requirements

  Create a complete limited entry decision table

Create a complete limited entry decision table

  Explain flow boundaries map

Explain flow boundaries map the dfd into a software architecture using transform mapping.

  Frame diagrams

Prepare a frame diagram for the software systems.

  Identified systems and elements of the sap system

Identify computing devices, which could be used to support Your Improved Process

  Design a wireframe prototype

Design a wireframe prototype to meet the needs of the personas and requirements.

  Explain the characteristics of visual studio 2005

Explain the characteristics of Visual Studio 2005.

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd