Question

Write a class called RationalNumber that represents a fraction with an integer numerator and denominator. A...

Write a class called RationalNumber that represents a fraction with an integer numerator and denominator. A RationalNumber object should have the following methods:

public RationalNumber(int numerator, int denominator)
Constructs a new rational number to represent the ratio (numerator/denominator). The denominator cannot be 0, so throw an IllegalArgumentException if 0 is passed.

public RationalNumber()
Constructs a new rational number to represent the ratio (0/1).

public int getDenominator()
Returns this rational number’s denominator value; for example, if the ratio is (3/5), returns 5.

public int getNumerator()
Returns this rational number’s numerator value; for example, if the ratio is (3/5), returns 3.

public String toString()
Returns a String representation of this rational number, such as "3/5". You may wish to omit denominators of 1, returning "4" instead of "4/1".

public boolean equals(Object other)
Returns true if this and other are equivalent RationalNumbers

public RationalNumber add(RationalNumber other)
Returns rational number that is this + other.

public RationalNumber subtract(RationalNumber other)
Returns rational number that is this - other.

public RationalNumber multiply(RationalNumber other)
Returns rational number that is this * other.

public RationalNumber divide(RationalNumber other)
Returns rational number that is this / other.

Your RationalNumber objects should always be in reduced form, avoiding rational numbers such as 3/6 in favor of 1/2, or avoiding 2/–3 in favor of –2/3. This may require the implementation of another method. Consider the Greatest Common Divisor (GCD) definition given in BJP4 Exercise 5.2: The GCD of two integers a and b is the largest integer that is a factor of both a and b. One efficient way to compute the GCD of two numbers is to use Euclid’s algorithm, which states the following:

GCD (a, b) = GCD (b, a % b) GCD (a, 0) = Absolute value of a

Use RationalNumberTest.java below to test your code. You will likely want to add additional tests.

import org.junit.Before;
import org.junit.Test;

import junit.framework.TestCase;

//TODO: Javadoc
public class RationalNumberTest extends TestCase {

private RationalNumber quarter;
private RationalNumber quarterNeg;
private RationalNumber twoOverEight;
private RationalNumber third;
private RationalNumber half;
private RationalNumber three;

@Before
public void setUp() {
quarter = new RationalNumber(1, 4);
quarterNeg = new RationalNumber(1, -4);
twoOverEight = new RationalNumber(2, 8);
third = new RationalNumber(1, 3);
half = new RationalNumber(1, 2);
three = new RationalNumber(6, 2);
}

@Test
public void testConstructor() {
RationalNumber def = new RationalNumber();
assertEquals("Default consturctor getter", 0, def.getNumerator());
assertEquals("Default consturctor getter", 1, def.getDenominator());
try {
new RationalNumber(3, 0);
fail("Didn't throw exception when denominator 0");
} catch (IllegalArgumentException e) {
assertEquals("Message for IllegalArgumentException for denominator 0", e.getMessage(),
"Denominator is 0");
}
}

@Test
public void testGetters() {

assertEquals("quarter getNumerator", 1, quarter.getNumerator());
assertEquals("quarter getDenominator", 4, quarter.getDenominator());

assertEquals("twoOverEight getNumerator", 1, twoOverEight.getNumerator());
assertEquals("twoOverEight getDenominator", 4, twoOverEight.getDenominator());

assertEquals("quarterNeg getNumerator", -1, quarterNeg.getNumerator());
assertEquals("quarterNeg getDenominator", 4, quarterNeg.getDenominator());

assertEquals("third getNumerator", 1, third.getNumerator());
assertEquals("third getDenominator", 3, third.getDenominator());

assertEquals("half getNumerator", 1, half.getNumerator());
assertEquals("half getDenominator", 2, half.getDenominator());

assertEquals("three getNumerator", 3, three.getNumerator());
assertEquals("three getDenominator", 1, three.getDenominator());
}

@Test
public void testToString() {
assertEquals("quarter toString", "1/4", quarter.toString());
assertEquals("quarterNeg toString", "-1/4", quarterNeg.toString());
assertEquals("twoOverEight toString", "1/4", twoOverEight.toString());
assertEquals("third toString", "1/3", third.toString());
assertEquals("half toString", "1/2", half.toString());
assertEquals("three toString", "3", three.toString());
}

@Test
public void testAdd() {
String desc = "quarter.add(twoOverEight)";
RationalNumber exp = half;
RationalNumber act = quarter.add(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarterNeg.add(twoOverEight)";
exp = new RationalNumber();
act = quarterNeg.add(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarter.add(third)";
exp = new RationalNumber(7, 12);
act = quarter.add(third);
assertEquals(desc, exp, act);

desc = "quarter.add(half)";
exp = new RationalNumber(3, 4);
act = quarter.add(half);
assertEquals(desc, exp, act);

// Running tests twice to make sure not modifying the objects

desc = "quarter.add(twoOverEight)";
exp = half;
act = quarter.add(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarterNeg.add(twoOverEight)";
exp = new RationalNumber();
act = quarterNeg.add(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarter.add(third)";
exp = new RationalNumber(7, 12);
act = quarter.add(third);
assertEquals(desc, exp, act);

desc = "quarter.add(half)";
exp = new RationalNumber(3, 4);
act = quarter.add(half);
assertEquals(desc, exp, act);
}

@Test
public void testSubtract() {

String desc = "quarter.subtract(twoOverEight)";
RationalNumber exp = new RationalNumber();
RationalNumber act = quarter.subtract(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarterNeg.subtract(twoOverEight)";
exp = new RationalNumber(1, -2);
act = quarterNeg.subtract(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarter.subtract(third)";
exp = new RationalNumber(-1, 12);
act = quarter.subtract(third);
assertEquals(desc, exp, act);

desc = "quarter.subtract(half)";
exp = new RationalNumber(-1, 4);
act = quarter.subtract(half);
assertEquals(desc, exp, act);

// Running tests twice to make sure not modifying the objects

desc = "quarter.subtract(twoOverEight)";
exp = new RationalNumber();
act = quarter.subtract(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarterNeg.subtract(twoOverEight)";
exp = new RationalNumber(1, -2);
act = quarterNeg.subtract(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarter.subtract(third)";
exp = new RationalNumber(-1, 12);
act = quarter.subtract(third);
assertEquals(desc, exp, act);

desc = "quarter.subtract(half)";
exp = new RationalNumber(-1, 4);
act = quarter.subtract(half);
assertEquals(desc, exp, act);
}

@Test
public void testMultiply() {

String desc = "quarter.multiply(twoOverEight)";
RationalNumber exp = new RationalNumber(1, 16);
RationalNumber act = quarter.multiply(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarterNeg.multiply(twoOverEight)";
exp = new RationalNumber(-1, 16);
act = quarterNeg.multiply(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarter.multiply(third)";
exp = new RationalNumber(1, 12);
act = quarter.multiply(third);
assertEquals(desc, exp, act);

desc = "quarter.multiply(half)";
exp = new RationalNumber(1, 8);
act = quarter.multiply(half);
assertEquals(desc, exp, act);

// Running tests twice to make sure not modifying the objects

desc = "quarter.multiply(twoOverEight)";
exp = new RationalNumber(1, 16);
act = quarter.multiply(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarterNeg.multiply(twoOverEight)";
exp = new RationalNumber(-1, 16);
act = quarterNeg.multiply(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarter.multiply(third)";
exp = new RationalNumber(1, 12);
act = quarter.multiply(third);
assertEquals(desc, exp, act);

desc = "quarter.multiply(half)";
exp = new RationalNumber(1, 8);
act = quarter.multiply(half);
assertEquals(desc, exp, act);
}

@Test
public void testDivide() {

String desc = "quarter.divide(twoOverEight)";
RationalNumber exp = new RationalNumber(1, 1);
RationalNumber act = quarter.divide(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarterNeg.divide(twoOverEight)";
exp = new RationalNumber(-1, 1);
act = quarterNeg.divide(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarter.divide(third)";
exp = new RationalNumber(3, 4);
act = quarter.divide(third);
assertEquals(desc, exp, act);

desc = "quarter.divide(half)";
exp = new RationalNumber(1, 2);
act = quarter.divide(half);
assertEquals(desc, exp, act);

// Running tests twice to make sure not modifying the objects
desc = "quarter.divide(twoOverEight)";
exp = new RationalNumber(1, 1);
act = quarter.divide(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarterNeg.divide(twoOverEight)";
exp = new RationalNumber(-1, 1);
act = quarterNeg.divide(twoOverEight);
assertEquals(desc, exp, act);

desc = "quarter.divide(third)";
exp = new RationalNumber(3, 4);
act = quarter.divide(third);
assertEquals(desc, exp, act);

desc = "quarter.divide(half)";
exp = new RationalNumber(1, 2);
act = quarter.divide(half);
assertEquals(desc, exp, act);

// Testing divide by zero

try {
quarter.divide(new RationalNumber(0, 4));
fail("Didn't throw exception when dividing 0");
} catch (IllegalArgumentException e) {
assertEquals("Message for IllegalArgumentException for dividing by 0", e.getMessage(),
"Denominator is 0");
}
}

@Test
public void testEquals() {
String desc = "quarter.equals(twoOverEight)";
boolean actB = quarter.equals(twoOverEight);
assertTrue(desc, actB);

desc = "quarterNeg.equals(new RationalNumber(-1, 4)";
actB = quarterNeg.equals(new RationalNumber(-1, 4));
assertTrue(desc, actB);

desc = "three.equals(new RationalNumber(-3,-1)";
actB = three.equals(new RationalNumber(-3, -1));
assertTrue(desc, actB);

desc = "quarter.equals(third)";
actB = quarter.equals(third);
assertFalse(desc, actB);

desc = "quarter.equals(half)";
actB = quarter.equals(half);
assertFalse(desc, actB);

desc = "quarter.equals(String)";
actB = quarter.equals("Hello");
assertFalse(desc, actB);

desc = "third.equals(new RationalNumber(2, 3)";
actB = third.equals(new RationalNumber(2, 3));
assertFalse(desc, actB);

desc = "quarter.equals(null)";
actB = quarter.equals(null);
assertFalse(desc, actB);
}

}

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


Given below is the code for the question. All Junit tests passed in the test class provided by instructor.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you

RationalNumber.java
==================

public class RationalNumber {
private int numerator, denominator;

public RationalNumber(int numerator, int denominator)
//Constructs a new rational number to represent the ratio (numerator/denominator). The denominator cannot be 0, so throw an IllegalArgumentException if 0 is passed.
{
if(denominator == 0)
throw new IllegalArgumentException("Denominator is 0");

this.numerator = numerator;
this.denominator = denominator;
if(denominator < 0)
{
this.denominator = -this.denominator;
this.numerator = - this.numerator;
}
simplify();
}
public RationalNumber()
//Constructs a new rational number to represent the ratio (0/1).
{
this.numerator = 0;
this.denominator = 1;
}
public int getDenominator()
//Returns this rational number’s denominator value; for example, if the ratio is (3/5), returns 5.
{
return denominator;
}
public int getNumerator()
//Returns this rational number’s numerator value; for example, if the ratio is (3/5), returns 3.
{
return numerator;
}
public String toString()
//Returns a String representation of this rational number, such as "3/5". You may wish to omit denominators of 1, returning "4" instead of "4/1".
{
if(denominator == 1)
return numerator + "";
else
return numerator + "/" + denominator;
}
public boolean equals(Object other)
//Returns true if this and other are equivalent RationalNumbers
{
if(other instanceof RationalNumber)
{
RationalNumber o = (RationalNumber) other;
if(numerator == o.numerator && denominator == o.denominator)
return true;
else
return false;
}
else
return false;
}


public RationalNumber add(RationalNumber other)
//Returns rational number that is this + other.
{
int n = numerator * other.denominator + other.numerator * denominator;
int d = denominator * other.denominator;
return new RationalNumber(n, d);
}

public RationalNumber subtract(RationalNumber other)
//Returns rational number that is this - other.
{
int n = numerator * other.denominator - other.numerator * denominator;
int d = denominator * other.denominator;
return new RationalNumber(n, d);
}
public RationalNumber multiply(RationalNumber other)
//Returns rational number that is this * other.
{
int n = numerator * other.numerator;
int d = denominator * other.denominator;
return new RationalNumber(n, d);
}

public RationalNumber divide(RationalNumber other)
//Returns rational number that is this / other.
{
int n = numerator * other.denominator;
int d = denominator * other.numerator;
return new RationalNumber(n, d);
}
private void simplify()
{
int gcd = GCD(numerator , denominator);
numerator /= gcd;
denominator /= gcd;
}

private int GCD(int a, int b)
{
if(b == 0)
return Math.abs(a);
else
return GCD(b, a % b);
}
}

Finished after 0.034 seconds Runs: 8/8 Errors: 0 Failures: 0 ▼铟RationalNumberTest [Runner: JUnit 4] (0.001 s) testAdd (0.001

Add a comment
Know the answer?
Add Answer to:
Write a class called RationalNumber that represents a fraction with an integer numerator and denominator. A...
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
  • java code Write a class called FractionObject that represents a fraction with an integer numerator and...

    java code Write a class called FractionObject that represents a fraction with an integer numerator and denominator as fields. A Fraction Object object should have the following methods: A constructor with int numerator, int denominator as parameters - Constructs a new fraction object to represent the ratio (numerator/denominator). The denominator cannot be 0, so output a message if O is passed and set the numerator and denominator to 1. A constructor with no parameters - Constructs a new FractionObject to...

  • Rational will be our parent class that I included to this post, Implement a sub-class MixedRational....

    Rational will be our parent class that I included to this post, Implement a sub-class MixedRational. This class should Implement not limited to: 1) a Constructor with a mathematically proper whole, numerator and denominator values as parameters. 2) You will override the: toString, add, subtract, multiply, and divide methods. You may need to implement some additional methods, enabling utilization of methods from rational. I have included a MixedRational class with the method headers that I used to meet these expectations....

  • Create a fraction class. This will have two attributes, a numerator and a denominator, both int....

    Create a fraction class. This will have two attributes, a numerator and a denominator, both int. This class will have constructors accessors and mutators (for the attributes) a toString method which will allow us to print the fraction in the form 3/4 an Add method so we can add two fractions a subtract method (subtracts one fraction from the other) a multiply method (multiply two fractions) a divide method (divides one fraction by the other) DO NOT (for now) worry...

  • Java code tasks: Please help with a single class (class Coord) in this program. This project...

    Java code tasks: Please help with a single class (class Coord) in this program. This project is called Panic! We will describe a single-level floorplan of a building, filled with different kinds of people and different kinds of threats. We will simulate how the people seek to evacuate the building to safety, and how the threats spread throughout the building. Various events will be announced, such as person movements, threats spawning, and people reaching safety or succumbing to the threats....

  • In Java, you'll find that it contains several methods that have not yet been finished. For now, the methods contain...

    In Java, you'll find that it contains several methods that have not yet been finished. For now, the methods contain only a placeholder return value so that the code will compile. Fill in your own implementation. public class SomePracticeStringMethods { /* * returns true if c is a letter in the word "temple" or false otherwise */ public static boolean inTU(char c) { /* placeholder just so that the function * compiles. fill in your implementation here. * * there...

  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • c++ Write a rational number class. A rational number is a number that can be written...

    c++ Write a rational number class. A rational number is a number that can be written as p/q where p and q are integers. The division is not carried out, only indicated. Thus you should represent rational numbers by two int values, numerator and denominator. Constructors must be present to create objects with any legal values. You should provide constructors to make objects out of pairs of int values; that is, a constructor with two int parameters. Since very int...

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

  • 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++ I am using visual studio for it. Make a copy of the Rational class you...

    C++ I am using visual studio for it. Make a copy of the Rational class you created in the previous Lab. Modify the class. Replace all your mathematical, input, and output functions with overloaded operators. Overload the following 12 operators: + - * / < > = = ! = <= >= >> << In order to test your class in your main function, prompt the user for a numerator and a denominator for your first object. Repeat the prompt...

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