Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Term 2 Assignment 1 - Fraction */
- /* A class which is used to represent fractions*/
- public class Fraction
- {
- private int numerator;
- private int denominator;
- // write default constructor
- public Fraction(){
- numerator = 1;
- denominator = 1;
- }
- // write constructor for fraction n/d where n, d > 0
- public Fraction(int n, int d){
- if(n > 0){
- numerator = n;
- }
- else{
- numerator = 1;
- }
- if(d > 0){
- denominator = d;
- }
- else{
- denominator = 1;
- }
- }
- // TODO write method to return fraction as a String
- public String toString(){
- return numerator+"/"+denominator;
- }
- // write method to return fraction as a mixed number String
- public String mixedNumber(){
- String toPrint = "";
- int tempInt = 0;
- int tempN = numerator;
- while(tempN >= denominator){
- tempN = tempN - denominator;
- tempInt = tempInt + 1;
- }
- tempN = numerator%denominator;
- if(tempN != 0){
- toPrint = toPrint + tempInt + " " + tempN + "/" + denominator;
- }
- if(tempN == 0){
- toPrint = tempInt + "";
- }
- if(tempN != 0 & tempInt == 0){
- toPrint = tempN + "/" + denominator;
- }
- return toPrint;
- }
- // write method to add fraction n/d to this Fraction
- public void add(int n, int d){
- if(n > 0 & d > 0){
- // a/b and c/d is(a*d + c*b)/(b*d).
- numerator *= d;
- n *= denominator;
- numerator = numerator / (denominator * d);
- denominator = denominator / (denominator * d);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement