int
fields, one for the numerator, the other for
the denominator. These values should be maintained so that they have
no factors in common (that way the fraction is in lowest terms). The
denominator value is always positive; the sign is carried by the
numerator. If the denominator is one, the fraction is really just a whole
number.
Implement the following constructors:
public Fraction() public Fraction( int value ) public Fraction( int numerator, int denominator ) public Fraction( String src ) public Fraction( Fraction src )The default constructor (
Fraction()
) should set the
fraction value to zero. The string constructor should parse the
string argument assuming it is either a (decimal) integer, or a
decimal integer followed by "/" followed by a nonzero (decimal)
integer. You can assume there are no signs, and there is no space
between the integers and the "/" character.
Implement the following accessors
public int getNumerator() public int getDenominator() public int getSign() public double value()and the corresponding mutators
public void setNumerator( int newNumerator ) public void setDenominator( int newDenominator )as well as these tests:
public boolean isZero() public boolean isUnity() public boolean equals( Fraction q )
For arithmetic operations, implement the following methods,
each of which returns a new Fraction
instance
(without modifying either this
or the argument).
public Fraction sum( Fraction augend ) public Fraction difference( Fraction subtrahend ) public Fraction product( Fraction multiplier ) public Fraction quotient( Fraction divisor ) public Fraction inverse() public Fraction negation()Also implement the following "in-place" operations that actually change the
this
instance:
public void add( Fraction augend ) public void subtract( Fraction subtrahend ) public void multiply( Fraction multiplier ) public void divide( Fraction divisor ) public void negate() public void invert()Finally, include a
toString
method.
An attempt to construct a fraction having a zero denominator (which is also an issue in the setDenominator() method) should cause your program to stop executing.
Here are some example text fractions:
1/2 500/1000 3/1 3 0/2 0Here
1/2
and 500/1000
both represent
one half, and the remaining examples are actually whole numbers.
The fraction calculator reads text fractions separated by a "+" or "-" operator; a fraction expression terminates with a ";" character. The fraction values are most naturally matched by way of regular expressions (implemented by the Pattern class in Java), but they are clumsy to use with the Java Scanner class. So you can make some assumptions, to keep it simple.
Input | Output | |
---|---|---|
4/8 ; | 1/2 |
|
1/2 + 1/4 ; | 3/4 |
|
13/73 - 1 + 1/3 + 4 ; | 769/219 |
Fraction.java
FractionDriver.java
FractionDriver.java
file.)