Marc Hauschildt
Web Technologies and Computer Software Development Instructor at Kirkwood Community College in Cedar Rapids, IA.
Week 2
Software Development Life Cycle, Steps 4-5
Fraction Class
public class Fraction {
private int numerator;
private int denominator;
public Fraction() {
numerator = 1;
denominator = 1;
}
public String toString() {
return numerator + "/" + denominator;
}
}
Generate a parameterized constructor that has two int parameters, called numerator and denominator. Assign both parameters to the instance variables.
public class Fraction {
// code omitted
public Fraction(int numerator, int denominator) {
setNumerator(numerator);
setDenominator(denominator);
}
public int getNumerator() {
return numerator;
}
public void setNumerator(int numerator) {
this.numerator = numerator;
}
public int getDenominator() {
return denominator;
}
public void setDenominator(int denominator) {
this.denominator = denominator;
}
}
package edu.kirkwood.model;
public class Fraction implements Comparable<Fraction> {
// Code omitted
@Override
public int compareTo(Fraction o) {
return 0;
}
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Fraction fraction = (Fraction) o;
return numerator == fraction.numerator && denominator == fraction.denominator;
}
@Override
public int hashCode() {
return Objects.hash(numerator, denominator);
}
public static int gcd(int a, int b) {
return 0;
}
public static int lcm(int a, int b) {
return 0;
}
public void simplify() {
}
public String toMixedNumber() {
return "";
}
public Fraction add(Fraction other) {
return null;
}
public Fraction subtract(Fraction other) {
return null;
}
public Fraction multiply(Fraction other) {
return null;
}
public Fraction divide(Fraction other) {
return null;
}
}
Static methods are called like this:
Fraction.gcd(15, 6); // 3
Fraction.lcm(15, 6); // 30
lcm(15, 6) // "Fraction" can be omitted if called inside the Fraction class.
Non-static methods are called like this
Fraction f1 = new Fraction(15, 6);
f1.simplify(); // 5/2
f1.toMixedNumber(); // 2 1/2
f1.getNumerator(); // 5
f1.getDenominator(); // 2
Fraction f2 = new Fraction(1, 3);
f1.add(f2); // 2 5/6
package edu.kirkwood.model;
/**
* Represents a fraction with an integer numerator and denominator.
* This class provides methods for fraction arithmetic, simplification,
* and comparison.
*/
public class Fraction implements Comparable<Fraction> {
private int numerator;
private int denominator;
/**
* Default constructor.
* Initializes a new fraction to 1/1.
*/
public Fraction() {
this.numerator = 1;
this.denominator = 1;
}
/**
* Constructs a fraction with a specified numerator and denominator.
*
* @param numerator the numerator of the fraction
* @param denominator the denominator of the fraction
*/
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
/**
* Gets the numerator of the fraction.
*
* @return the numerator
*/
public int getNumerator() {
return numerator;
}
/**
* Sets the numerator of the fraction.
*
* @param numerator the new numerator
*/
public void setNumerator(int numerator) {
this.numerator = numerator;
}
/**
* Gets the denominator of the fraction.
*
* @return the denominator
*/
public int getDenominator() {
return denominator;
}
/**
* Sets the denominator of the fraction.
*
* @param denominator the new denominator
* @throws ArithmeticException if the denominator is zero
*/
public void setDenominator(int denominator) {
this.denominator = denominator;
}
/**
* Returns a string representation of the fraction in the format "numerator/denominator".
*
* @return a string representation of the fraction
*/
@Override
public String toString() {
// Implementation needed
return "";
}
/**
* Compares this fraction to another fraction.
*
* @param o the other Fraction to be compared.
* @return a negative integer, zero, or a positive integer.
*/
@Override
public int compareTo(Fraction o) {
// Implementation needed
return 0;
}
/**
* Determines if two fraction objects are the same
*
* @param o the other object to be compared.
* @return a boolean true is both objects are the same, false otherwise
*/
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
Fraction fraction = (Fraction) o;
return numerator == fraction.numerator && denominator == fraction.denominator;
}
/**
* This method is supported for the benefit of hash tables such as HashMap and HashSet.
*
* @return an integer representing a hash code value for this object.
*/
@Override
public int hashCode() {
return Objects.hash(numerator, denominator);
}
/**
* Calculates the greatest common divisor (GCD) of two integers.
*
* @param a the first integer
* @param b the second integer
* @return the greatest common divisor of a and b
*/
public static int gcd(int a, int b) {
// Implementation needed
return 0;
}
/**
* Calculates the least common multiple (LCM) of two integers.
*
* @param a the first integer
* @param b the second integer
* @return the least common multiple of a and b
*/
public static int lcm(int a, int b) {
// Implementation needed
return 0;
}
/**
* Simplifies this fraction to its lowest terms by dividing the numerator
* and denominator by their greatest common divisor.
*/
public void simplify() {
// Implementation needed
}
/**
* Converts this fraction to a mixed number string representation (e.g., "1 2/3").
* If the fraction is a proper fraction, it returns the fraction itself.
*
* @return a string representation of the fraction as a mixed number
*/
public String toMixedNumber() {
// Implementation needed
return "";
}
/**
* Adds another fraction to this fraction.
*
* @param other the fraction to add
* @return a new Fraction object representing the sum
*/
public Fraction add(Fraction other) {
// Implementation needed
return null;
}
/**
* Subtracts another fraction from this fraction.
*
* @param other the fraction to subtract
* @return a new Fraction object representing the difference
*/
public Fraction subtract(Fraction other) {
// Implementation needed
return null;
}
/**
* Multiplies this fraction by another fraction.
*
* @param other the fraction to multiply by
* @return a new Fraction object representing the product
*/
public Fraction multiply(Fraction other) {
// Implementation needed
return null;
}
/**
* Divides this fraction by another fraction.
*
* @param other the fraction to divide by (the divisor)
* @return a new Fraction object representing the quotient
* @throws IllegalArgumentException if the divisor is zero
*/
public Fraction divide(Fraction other) {
// Implementation needed
return null;
}
}
Create a new private respository on GitHub titled something like "Java2MathCalculators". Copy the URL.
Open the Terminal in IntelliJ. Enter this command:
git remote add origin <paste-your-url>
Go to the Commit tab. Disable the "Analyze Code" feature in the Settings pop-out.
Check all of the boxes under "Changes" and "Unversioned Files".
Type a commit message like "Created Fraction class".
Press the "Commit and Push" button.
Review the files committed, then press "Push".
View the files on GitHub.
Add "mlhaus" as a collaborator under the Settings tab.
| Fraction |
|---|
| - int numerator - int denominator |
| + Fraction() + Fraction(int numerator, int denominator) + getNumerator() :: int + setNumerator(int numerator) :: void + getDenominator() :: int + setDenominator(int denominator) :: void + toString() :: String + compareTo(Fraction other) :: int + equals(Object other) :: boolean + hashCode() :: int + gcd(int a, int b) :: int + lcm(int a, int b) :: int + simplify() :: void + toMixedNumber() :: String + add(Fraction other) :: Fraction + subtract(Fraction other) :: Fraction + multiply(Fraction other) :: Fraction + divide(Fraction other) :: Fraction |
classDiagram
class Fraction {
- int numerator
- int denominator
+ Fraction()
+ Fraction(int numerator, int denominator)
+ getNumerator(): int
+ setNumerator(int numerator): void
+ getDenominator(): int
+ setDenominator(int denominator): void
+ toString() : String
+ compareTo(Fraction other) : int
+ equals(Object other) : boolean
+ hashCode() : int
+ simplify() : void
+ gcd(int a, int b): int
+ toMixedNumberString() : String
+ add(Fraction other) : Fraction
+ subtract(Fraction other) : Fraction
+ multiply(Fraction other) : Fraction
+ divide(Fraction other) : Fraction
}
Run this command if your project is not set up with Git.
git init -b main
Run this command if your project's default branch is not "main".
git checkout -b main
Run these commands in the terminal one at a time
git remote add origin <https://github.com/your-username/your-repo-name.git>
git add .
git commit -m "Started Fraction calculator, September XX"
git push origin main
If you get a srcrefspec error, run this command:
git checkout -b main
Add "mlhaus" as a collaborator.
git init -b main
git checkout -b main
git remote add origin https://github.com/YOUR-USERNAME/java-calculators.git
git add .
git commit -m "Your message"
git config --global user.name "YOUR FULL NAME"git config --global user.email "YOUR EMAIL ADDRESS"
git config --global credential.helper cache
In IntelliJ, right-click the Fraction class title and choose "Show Context Options" then "Create Test".
JUnit 5 will be pre-selected, click the "Fix" button if shown.
Check the "setUp/@Before" box.
Click the check boxes next to all of the methods.
Click one method name, press Ctrl + A, press the spacebar
The FractionTest class is successfully added to the tests folder.
Fully-qualified annotations ("@org.junit.jupiter.api.BeforeEach" and "@org.junit.jupiter.api.Test") only need to be @BeforeEach and @Test.
If your annotations are fully-qualified press Ctrl + R to open the find and replace menu.
Replace all references of "@org.junit.jupiter.api." with "@".
Add an import statement for @BeforeEach and @Test.
Some Unit Tests require a default instance of the class.
The setUp method can be used to instantiate that object needed for each test.
Create two new Fraction objects as a private instance variables.
Instantiate the Fraction objects in the setUp method.
We want to keep our code DRY (Don't Repeat Yourself). If we don't use the setUp method we will have to instantiate a Fraction object inside of every single test method.
private Fraction f1;
private Fraction f2;
@BeforeEach
void setUp() {
f1 = new Fraction();
f2 = new Fraction(2, 3);
}If you run the tests now, it should say all tests passed and you will see green checkmarks next to the method names in the bottom-left corner. We actually want all tests to fail by default.
Highlight a set of curly brackets on one of the tests.
Press Ctrl+Cmd+G (Mac) or Shift+Ctrl+Alt+J (Windows) to select all occurrences.
Use the arrow keys to position the cursors inside the curly brackets and type a fail method.
fail();
This is a static method from the Assertions class of JUnit.
Run the FractionTest class again to see that all tests failed. You will see orange X's next to the method names.
Study the assertEquals methods from JUnit's Assertions class.
Write tests for all of the getters and toString.
You should test all getter methods before setter methods so you can safely use the getter methods to verify that the setter methods work correctly.
When using the assertEquals method the first argument is the expected value and the second argument is the actual value.
The actual value will always come from a getter method.
@Test
void getNumerator() {
assertEquals(1, f1.getNumerator());
assertEquals(2, f2.getNumerator());
}
@Test
void getDenominator() {
assertEquals(1, f1.getDenominator());
assertEquals(3, f2.getDenominator());
}
@Test
void testToString() {
assertEquals("1/1", f1.toString());
assertEquals("2/3", f2.toString());
}Next, we will write tests for all of the setters
For setNumerator, set a positive, 0, and negative value. Call the getNumerator and toString methods to ensure equality.
For setDenominator, set a positive and negative value. Call the getDenominator and toString methods to ensure equality.
The denominator negative test will fail because "1/-3" will be returned instead of "-1/3" as I want.
An optional third parameter can be used for a message.
@Test
void setNumeratorPostive() {
// Act
f1.setNumerator(3);
// Assert
assertEquals(3, f1.getNumerator());
assertEquals("3/1", f1.toString());
}
@Test
void setNumeratorZero() {
// Act
f1.setNumerator(0);
// Assert
assertEquals(0, f1.getNumerator());
assertEquals("0/1", f1.toString());
}
@Test
void setNumeratorNegative() {
// Act
f1.setNumerator(-3);
// Assert
assertEquals(-3, f1.getNumerator());
assertEquals("-3/1", f1.toString());
}
@Test
void setDenominatorPostive() {
// Act
f1.setDenominator(3);
// Assert
assertEquals(3, f1.getDenominator());
assertEquals("1/3", f1.toString());
}
@Test
void setDenominatorNegative() {
// Act
f1.setDenominator(-3);
// Assert
assertEquals(-3, f1.getDenominator());
assertEquals("-1/3", f1.toString());
}
@Test
void setNumeratorAndDenominatorNegative() {
// Act
f1.setNumerator(-3);
f1.setDenominator(-3);
// Assert
assertEquals("3/3", f1.toString());
}Because the denominator cannot be 0, we use assertThrows.
The first argument is the type of Exception you expect to be thrown, in this case ArithmeticException.
The second argument is a lambda expression that calls the abstract method from the Executable functional interface.
assertThrows returns a Throwable object of type T. In this case, a reasonable Throwable object to use is ArithmeticException. You can assert the Exception message.
@Test
void setDenominatorZero() {
// Act and Assert
assertThrows(ArithmeticException.class, () -> f1.setDenominator(0));
ArithmeticException e = assertThrows(ArithmeticException.class, () -> f1.setDenominator(0));
assertEquals("Denominator cannot be zero", e.getMessage());
}After writing the unit tests, go back to the regular class and implement the code that will get the test to pass.
public void setDenominator(int denominator) {
if(denominator == 0){
throw new ArithmeticException("Denominator cannot be zero");
}
if(denominator < 0 && numerator > 0 || denominator < 0 && numerator < 0) {
numerator *= -1;
denominator *= -1;
}
this.denominator = denominator;
}Update the parameterized constructor to call the setter methods to validate the input, rather than potentially assigning invalid values to the attributes.
public Fraction(int numerator, int denominator) {
setNumerator(numerator);
setDenominator(denominator);
}The following assertions seem logical, but they don't fully test it.
To correctly test the greatest common denominator of two integers, we must test for positive and negative values.
Call assertTrue by passing a single boolean expression.
@Test
void gcd() {
assertEquals(15, Fraction.gcd(75, 45));
assertEquals(2, Fraction.gcd(2, 4));
assertEquals(1, Fraction.gcd(5, 7));
int result1 = Fraction.gcd(5, 7);
int result2 = Fraction.gcd(-5, 7);
int result3 = Fraction.gcd(5, -7);
int result4 = Fraction.gcd(-5, -7);
assertTrue(result1 == result2 && result2 == result3 && result3 == result4);
}@Test
void gcd() {
assertEquals(15, Fraction.gcd(75, 45));
assertEquals(2, Fraction.gcd(2, 4));
assertEquals(1, Fraction.gcd(5, 7));
}We will use this solution.
If you run the unit test now, it will fail.
Update the Fraction class gcd method to return Math.abs(a).
public static int gcd(int a, int b) {
if (b == 0) {
return Math.abs(a);
}
return gcd(b,a % b);
}public String toMixedNumber() {
simplify();
if(denominator == 1) {
return numerator + "";
} else {
return toString();
}
}public String toMixedNumber() {
simplify();
if(denominator == 1) {
return numerator + "";
} else if(Math.abs(numerator) > denominator) {
int wholeNumber = Math.abs(numerator) / denominator;
int remainder = Math.abs(numerator) % denominator;
return (numerator < 0 ? "-" : "") + wholeNumber + " " + remainder + "/" + denominator;
} else if(numerator == 0) {
return "0";
} else {
return toString();
}
}Go to the Commit tab.
Check all of the boxes under "Changes" and "Unversioned Files".
Type a commit message like "Created FractionTest class".
Press the "Commit and Push" button.
Review the files committed, then press "Push".
View the files on GitHub.
By Marc Hauschildt
Web Technologies and Computer Software Development Instructor at Kirkwood Community College in Cedar Rapids, IA.