SHARE
TWEET

marco fractions

a guest Jan 21st, 2020 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Term 2 Assignment 1 - Fraction */
  2. /* A class which is used to represent fractions*/
  3. public class Fraction
  4. {
  5.   private int numerator;
  6.   private int denominator;
  7.  
  8.   // write default constructor
  9.   public Fraction(){
  10.     numerator = 1;
  11.     denominator = 1;
  12.   }
  13.  
  14.   // write constructor for fraction n/d where n, d > 0
  15.   public Fraction(int n, int d){
  16.     if(n > 0){
  17.       numerator = n;
  18.     }
  19.     else{
  20.       numerator = 1;
  21.     }
  22.  
  23.     if(d > 0){
  24.       denominator = d;
  25.     }
  26.     else{
  27.       denominator = 1;
  28.     }
  29.  
  30.   }
  31.  
  32.   // TODO write method to return fraction as a String
  33.   public String toString(){
  34.     return numerator+"/"+denominator;
  35.   }
  36.  
  37.   // write method to return fraction as a mixed number String
  38.   public String mixedNumber(){
  39.     String toPrint = "";
  40.     int tempInt = 0;
  41.     int tempN = numerator;
  42.  
  43.     while(tempN >= denominator){
  44.       tempN = tempN - denominator;
  45.       tempInt = tempInt + 1;
  46.     }
  47.     tempN = numerator%denominator;
  48.    
  49.     if(tempN != 0){
  50.       toPrint = toPrint + tempInt + " " + tempN + "/" + denominator;
  51.     }
  52.     if(tempN == 0){
  53.       toPrint = tempInt + "";
  54.     }
  55.     if(tempN != 0 & tempInt == 0){
  56.       toPrint = tempN + "/" + denominator;
  57.     }
  58.     return toPrint;
  59.   }
  60.  
  61.   // write method to add fraction n/d to this Fraction
  62.   public void add(int n, int d){
  63.     if(n > 0 & d > 0){
  64.       // a/b and c/d is(a*d + c*b)/(b*d).
  65.       numerator *= d;
  66.       n *= denominator;
  67.       numerator = numerator / (denominator * d);
  68.       denominator = denominator / (denominator * d);
  69.     }
  70.   }
  71. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top