# Fraction class that does the 4 main calculation functions

Page 1 of 1

## 8 Replies - 69890 Views - Last Post: 26 June 2013 - 05:11 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=87241&amp;s=b0616c51164c2395c57a88fc4f5dce89&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Lucrosen

Reputation: 5
• Posts: 21
• Joined: 11-February 09

# Fraction class that does the 4 main calculation functions

Posted 17 February 2009 - 09:26 AM

Hi,
This is my latest java project in my 2nd level java course. This code functions properly and works well with my driver class(not uploaded). I am wondering if there are any improvements i could make to the code as well as wondering about my tabbing and commenting. My instructor has not really explained to us what we should comment and what we shouldn't comment.
```/* Fraction methods for adding, subtracting, multiplying, and dividing rational number
* also will have to compute greatest common denominator for use with the add/subtract
* feature and can reduce the numbers after the appropriate operations have been completed.
* version 1.3
*/

public class Fraction
{
private int num;  //numerator
private int den;  //denominator

public Fraction(int n, int d) // constructor that requires 2 digits of input
{
// assign num = n & den = d as long as d!= 0
if(d != 0)
{
num = n;
den = d;
}
else
System.exit(0);
}
private static int gcd(int x, int y)
{
/* gcd() method finds the greatest common divisor of
* the 2 int variables passed and returns that value
*
*/
int mod; // hold a value temporarily to allow switch
if(x < y) // always use the larger value as the divisor
{
mod = x;
x = y;
y = mod;
}
int r = x % y; // r holds the remainder of modulus division
while (r != 0)  // while modulus division does not result in zero
{
x = y;
y = r;
r = x % y;
}
return y;

}
private Fraction reduce(int n, int d)
{
int gcdNum = gcd(n,d);

d = d / gcdNum; // reduce the denominator using the gcd foun in gcd method
n = n / gcdNum; // reduce the numerator using the gcd foun in gcd method
return new Fraction(n,d);	// return the new fraction object in lowest form
}
{
int num1 = (this.num * b.den) + (b.num * this.den); // cross multily and add
int	num2 = this.den * b.den; // multiply the denominators to make them equivlent

return reduce(num1,num2);// calls reduce() method and returns a new Fraction object

}
public Fraction subtract(Fraction b)
{
int num1 = (this.num * b.den) - (b.num * this.den);// cross multiply and subtact
int num2 = this.den * b.den;

return reduce(num1,num2);// sends to reduce method
}
public Fraction multiply(Fraction b)
{
int num1 = this.num * b.num; // multiplys straight accross
int	num2 = this.den * b.den;

return reduce(num1,num2);// sends to reduce method and returns the reduced fraction to the toString() method
}
public Fraction divide(Fraction b)
{
int num1 = this.num * b.den; //multiplys the inverse of 2nd fraction object to divide
int num2 = this.den * b.num;

return reduce(num1, num2);// sends to reduce method
}
public String toString()  // *** convert to a mixed fraction for output only
{
if(num > den && den > 1)	 //if true will show fraction object and mixed number
return (num + "/" + den + " or " + (num/den) + " " + (num % den) + "/" + den);
else
return(num + "/" + den); //will not try to convert fraction object to mixed number
}
}

```

Thank you very much for any and all input
~Luc

Is This A Good Question/Topic? 1

## Replies To: Fraction class that does the 4 main calculation functions

### #2 mostyfriedman

• The Algorithmi

Reputation: 729
• Posts: 4,473
• Joined: 24-October 08

## Re: Fraction class that does the 4 main calculation functions

Posted 17 February 2009 - 09:32 AM

you can improve the gcd method by
```while(x != y)
{
if( x > y)
x -= y;
else
y -= x
}
return x;

```

### #3 NickDMax

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: Fraction class that does the 4 main calculation functions

Posted 17 February 2009 - 10:17 AM

Javadocs! -- a Quick and easy way to generate documentation for your code. Basically it is way to generate API documentation much like you find on for the JDK.

Javadoc is a utility that scans you source code an extracts specially marked comment blocks and formats them into a HTML document so that they can be read with a browser.

Javadocs also integrate well into most IDE's allowing your classes and methods and members to have content specific help.

Generally to insert a javadoc you use the special opening

/**

This is just like the normal opening comment /* but has an extra little star.

```/** Fraction contains methods for adding, subtracting, multiplying, and dividing rational numbers
* also has the ability to compute greatest common denominator for use with the add/subtract
* feature and can reduce the numbers after the appropriate operations have been completed.
* @Version 1.3
* @Author YourNameHere
*/
```

The little @ is a way of passing special info to the javadoc app for its formatting. For example we told it the version and author in this little comment.

You should place javadocs at a minimum before each class, and each public method.

```	 /**
* Class constructor for the creation of a rational number. A rational number is a number of the form n/m where
*  n and m are integers and m is non-zero.
* @param n - an integer numerator (the number on top of a fraction).
* @param m - a non-zero integer denominator. Note that a value of zero will result in an System.exit(0) call!!
*/
public Fraction(int n, int d) // constructor that requires 2 digits of input
{
// assign num = n & den = d as long as d!= 0
if(d != 0)
{
num = n;
den = d;
}
else
System.exit(0);
}
```

Even if you never generate the HTML the javadoc conventions help you maintain good documentation habits (such as explaining the parameters to methods) and they come in handy within IDE's.

For a quick rundown on how to format javadocs look at sun's tutorial.

Me, I try to place a java doc before all Classes/Enums/Interfaces, Methods, and Member variables. Don't place javadocs inside of methods as this really has no function. Besides, inside of methods you want to use the // style of comments rather than block comments -- the reason for this is that block comments don't nest. Most IDE's have a neat little "Comment All" function that allows you to hilight a block of code and comment it out with the // style comments.

Later you may wish to stray away from javadocs proper (since they can be a little hard to read when people start adding HTML tags and lots of links and etc. (i.e. the point where you need a WYSIWYG editor for your comments) there are other documentation generators that tend to keep things a little more pure and less convoluted.

This post has been edited by NickDMax: 17 February 2009 - 10:54 AM

### #4 NickDMax

Reputation: 2255
• Posts: 9,245
• Joined: 18-February 07

## Re: Fraction class that does the 4 main calculation functions

Posted 17 February 2009 - 11:23 AM

A couple of notes (beyond the scope of a beginning java course) about java programming.

You class is basically an immutable object -- that is none of your methods actually edit the internal data (they don't "change the state" of the object). This allows you to make your class implement an immutable object.

immutable object are handy because they are thread safe and therefore save the users of the class a headache when trying to use the class in concurrent programs. Immutable objects are used a good deal in Java (for example String is immutable).

immutable objects DO have the unfortunate cost associated in creating a new instance every time you change the data... but there are benefits as well.

To make your class implement immurable objects just make your two private members final:
```	private final int num;  //numerator
private final int den;  //denominator

```
-- this causes an error in your constructor but you can get rid of that by just setting num and dem to zero in you else block -- OR see my note about Exceptions below.

Other Notes (completing the class):

Rather than exiting upon upon a bad parameter being passed, you can throw an exception and allow the user of this class a chance to deal with her mistake:
```		 public Fraction(int n, int d) // constructor that requires 2 digits of input
{
// assign num = n & den = d as long as d!= 0
if(d != 0)
{
num = n;
den = d;
} else {
throw new IllegalArgumentException("Denominator can not be zero!");

}
}
```

You may also wish to define methods for getting the values of your members:
```public getNumerator() { return num; }
public getDenominator() { return dem; }

```

Who knows maybe the users of this class may find that useful later. -- You should always strive to implement a FULL CLASS even if you don't really need all of the functions at the time, you may later, and they may come in handy for other programmers (then again... you have to take the time to TEST all of the methods even if you don't use them an this can be irritating).

You may also want to override the .equals() method. Right now if I have frac1 = 1/2 and frac2 = 2/4 the frac1.equals(frac2) does not return true. In face if I make both frac1 and frac2 1/2 then frac1.equals(frac2) STILL does not return the right value since it is checking if frac1==frac2 which is asking if they are the same object.

### #5 JohnRambo

Reputation: 0
• Posts: 4
• Joined: 17-February 09

## Re: Fraction class that does the 4 main calculation functions

Posted 17 February 2009 - 03:14 PM

About GCD, you can also find it this way...

```	private static int gcd(int y, int x)
{
if (x == 0)
return y;
else
return gcd(x, y%x);
}

```

### #6 jane010794

Reputation: 0
• Posts: 4
• Joined: 07-December 10

## Re: Fraction class that does the 4 main calculation functions

Posted 07 December 2010 - 09:20 PM

you can also use this one
```/**
*Returns the reduced(simpliest) form of this fraction
**/
public Fraction reduce(){
Fraction r= new Fraction(); // construct a fraction
int gCF = computeGCF(); // determine the greatest common factor of numerator and denominator
int newN= numerator/gCF; //compute newN, the numerator of the simpliest form of this fraction
//compute newD, the denominator of the simpliest form of this fraction
int newD = denominator/gCF;
r.setNumerator(newN); // set the numerator of the simpliest form to newN
r.setDenominator(newD);// set the denominator of the simpliest form to newD
return r; // return the simpliest form of this fraction
}
// Compuets the greastest common factor of the numerator and denominator
private int computeGCF(){
int gCF=1;
int lesser = 1;
boolean found=false;
lesser = computeLesser(numerator, denominator);
for (int candidate= lesser; (candidate >= 1 && !found); candidate--){
if (numerator%candidate == 0 && denominator%candidate==0){
found = true;
gCF= candidate;
}
}
return gCF;
}
//Returns the lesser integer between n1 and n2
private int computeLesser(int n1, int n2){
int lesser=0;
if (n1<n2)
lesser = n1;
else
lesser = n2;
return lesser;
}

```

This post has been edited by macosxnerd101: 07 December 2010 - 09:26 PM
Reason for edit:: Please use code tags

### #7 pbl

• There is nothing you can't do with a JTable

Reputation: 8378
• Posts: 31,956
• Joined: 06-March 08

## Re: Fraction class that does the 4 main calculation functions

Posted 07 December 2010 - 09:35 PM

JohnRambo, on 17 February 2009 - 04:14 PM, said:

About GCD, you can also find it this way...

```	private static int gcd(int y, int x)
{
if (x == 0)
return y;
else
return gcd(x, y%x);
}

```

Really cute

Reputation: -3
• Posts: 14
• Joined: 25-June 13

## Re: Fraction class that does the 4 main calculation functions

Posted 25 June 2013 - 10:42 PM

Lucrosen, on 17 February 2009 - 09:26 AM, said:

Hi,
This is my latest java project in my 2nd level java course. This code functions properly and works well with my driver class(not uploaded). I am wondering if there are any improvements i could make to the code as well as wondering about my tabbing and commenting. My instructor has not really explained to us what we should comment and what we shouldn't comment.
```/* Fraction methods for adding, subtracting, multiplying, and dividing rational number
* also will have to compute greatest common denominator for use with the add/subtract
* feature and can reduce the numbers after the appropriate operations have been completed.
* version 1.3
*/

public class Fraction
{
private int num;  //numerator
private int den;  //denominator

public Fraction(int n, int d) // constructor that requires 2 digits of input
{
// assign num = n & den = d as long as d!= 0
if(d != 0)
{
num = n;
den = d;
}
else
System.exit(0);
}
private static int gcd(int x, int y)
{
/* gcd() method finds the greatest common divisor of
* the 2 int variables passed and returns that value
*
*/
int mod; // hold a value temporarily to allow switch
if(x < y) // always use the larger value as the divisor
{
mod = x;
x = y;
y = mod;
}
int r = x % y; // r holds the remainder of modulus division
while (r != 0)  // while modulus division does not result in zero
{
x = y;
y = r;
r = x % y;
}
return y;

}
private Fraction reduce(int n, int d)
{
int gcdNum = gcd(n,d);

d = d / gcdNum; // reduce the denominator using the gcd foun in gcd method
n = n / gcdNum; // reduce the numerator using the gcd foun in gcd method
return new Fraction(n,d);	// return the new fraction object in lowest form
}
{
int num1 = (this.num * b.den) + (b.num * this.den); // cross multily and add
int	num2 = this.den * b.den; // multiply the denominators to make them equivlent

return reduce(num1,num2);// calls reduce() method and returns a new Fraction object

}
public Fraction subtract(Fraction B)/>
{
int num1 = (this.num * b.den) - (b.num * this.den);// cross multiply and subtact
int num2 = this.den * b.den;

return reduce(num1,num2);// sends to reduce method
}
public Fraction multiply(Fraction B)/>
{
int num1 = this.num * b.num; // multiplys straight accross
int	num2 = this.den * b.den;

return reduce(num1,num2);// sends to reduce method and returns the reduced fraction to the toString() method
}
public Fraction divide(Fraction B)/>
{
int num1 = this.num * b.den; //multiplys the inverse of 2nd fraction object to divide
int num2 = this.den * b.num;

return reduce(num1, num2);// sends to reduce method
}
public String toString()  // *** convert to a mixed fraction for output only
{
if(num > den && den > 1)	 //if true will show fraction object and mixed number
return (num + "/" + den + " or " + (num/den) + " " + (num % den) + "/" + den);
else
return(num + "/" + den); //will not try to convert fraction object to mixed number
}
}

```

Thank you very much for any and all input
~Luc

Please can you posy your main class in doing this fraction class...need it in my project...please I'm begging you tomorrow is our deadline of submission...Thanks,...:-)

### #9 cfoley

• Cabbage

Reputation: 2388
• Posts: 5,013
• Joined: 11-December 07

## Re: Fraction class that does the 4 main calculation functions

Posted 26 June 2013 - 05:11 AM

```	private Fraction reduce(int n, int d) {
int gcdNum = gcd(n, d);
d = d / gcdNum;
n = n / gcdNum;
return new Fraction(n, d);
}

```

This is correct but it's generally considered bad style to modify the parameters in Java. I would just do this:

```	private Fraction reduce(int n, int d) {
int gcd = gcd(n, d);
return new Fraction(n / gcd, d / gcd);
}

```

```	public Fraction add(Fraction b) {
int num1 = (this.num * b.den) + (b.num * this.den);
int num2 = this.den * b.den;
return reduce(num1, num2);
}

public Fraction subtract(Fraction b) {
int num1 = (this.num * b.den) - (b.num * this.den);
int num2 = this.den * b.den;
return reduce(num1, num2);
}

```

Notice how the code for these two methods is almost identical. I would write these like this:

```	public Fraction add(Fraction b) {
int numerator = (num * b.den) + (b.num * den);
return reduce(numerator, den * b.den);
}

public Fraction subtract(Fraction b) {
}

public Fraction negative() {
return new Fraction(-num, den);
}

```

Advantages: if you have a bug in the addition algorithm, thee is only one place to fix it, subtract becomes simpler, you get an additional public method that might be useful elsewhere. Disadvantages, the computer is doing slightly more work to subtract. I don't think you will ever notice it but there is a chance if you are doing thousands or millions of subtractions.

It's the same with multiplication and division:

```	public Fraction multiply(Fraction b) {
return reduce(num * b.num, den * b.den);
}

public Fraction divide(Fraction b) {
return multiply(b.reciprocal());
}

public Fraction reciprocal() {
return new Fraction(den, num);
}

```

You could make negative() and reciprocal() private but I think they could be generally useful functions.

Finally, in your constructor, you have some error checking but you don't take signs into account. A positive or negative numerator could be supplied as could a positive or negative denominator. I would do something like this to combine the signs into the numerator and always have a positive deniminator:

```	public Fraction(int n, int d) {
if (d == 0) {
throw new IllegalArgumentException("Denominator cannot be zero.");
} else if (d < 0) {
num = -n;
den = -d;
} else {
num = n;
den = d;
}
}

```

Here is how I would format your entire class:

```/**
* Fraction methods for adding, subtracting, multiplying, and dividing rational
* number also will have to compute greatest common denominator for use with the
* add/subtract feature and can reduce the numbers after the appropriate
* operations have been completed. version 1.3
*/
public class Fraction {
private final int num;
private final int den;

public Fraction(int n, int d) {
if (d == 0) {
throw new IllegalArgumentException("Denominator cannot be zero.");
} else if (d < 0) {
num = -n;
den = -d;
} else {
num = n;
den = d;
}
}

int numerator = (num * b.den) + (b.num * den);
return reduce(numerator, den * b.den);
}

private Fraction reduce(int n, int d) {
int gcd = gcd(n, d);
return new Fraction(n / gcd, d / gcd);
}

private static int gcd(int x, int y) {
return (x == 0) ? y : gcd(y, x % y);
}

public Fraction subtract(Fraction b) {
}

public Fraction negative() {
return new Fraction(-num, den);
}

public Fraction multiply(Fraction b) {
return reduce(num * b.num, den * b.den);
}

public Fraction divide(Fraction b) {
return multiply(b.reciprocal());
}

public Fraction reciprocal() {
return new Fraction(den, num);
}

@Override
public String toString() {
if (num > den && den > 1) {
return (num + "/" + den + " or " + (num / den) + " " + (num % den) + "/" + den);
} else {
return (num + "/" + den);
}
}
}

```

This post has been edited by cfoley: 26 June 2013 - 05:15 AM

Page 1 of 1

 .related ul { list-style-type: circle; font-size: 12px; font-weight: bold; } .related li { margin-bottom: 5px; background-position: left 7px !important; margin-left: -35px; } .related h2 { font-size: 18px; font-weight: bold; } .related a { color: blue; }