# Fraction Calculator need help

• 04-05-2010, 11:08 PM
Fraction Calculator need help
Hey guys. I am working on a program that does simple calculations on fractions like add, subtract, etc...My program needs to be able to accept the fractions from scanner.nextLine() form and not individual numerator = scanner.nextInt() or anything like that. It can accept improper or proper fractions (ie. 1 1/3 or 4/3). The entire list of rules is here (Project 3).

My main problem is how do I accept the numbers from the scanner without asking for the individual numbers like numerator and then denominator and such. Then how do I mutate them into a improper fraction for calculations?

Any help is much appreciated!
• 04-05-2010, 11:28 PM
Fubarable
There's a link on the assignment page which gives you a parse method. If it were me, I'd just use that.
• 04-05-2010, 11:44 PM
I read through the parse method (to the best of my ability that is lol), and I wasn't sure exactly what it was doing. Does it read it as a string and return the value as a string? Or is it doing something else there. I guess what I'm asking is how would I use that method?

Also, thanks for taking the time to read all that and help me out!
• 04-05-2010, 11:51 PM
Fubarable
Quote:

I read through the parse method (to the best of my ability that is lol), and I wasn't sure exactly what it was doing. Does it read it as a string and return the value as a string? Or is it doing something else there. I guess what I'm asking is how would I use that method?

First thing I read are the code author's comments. And it states at the very top of that link:
Code:

```/*   This method takes a String representation of a (proper or improper)   fraction and returns a corresponding instance of Fraction.  If the   String is invalid null is returned. */```

Seems pretty clear what it's doing to me based on this.
• 04-06-2010, 12:08 AM
True, I guess I needed reassurance. So to create a instance of fraction to be displayed I would do something like this?

Code:

```String fract;                 Scanner scan = new Scanner(System.in);                                                 System.out.print("Enter a fraction: ");                 fract = scan.nextLine();                        Fraction currentFract = parseFraction(fract);                 System.out.println(currentFract);```
• 04-06-2010, 12:17 AM
Fubarable
You may not like me for this, but really the best answer is "try it and see". I would test using this static method on a couple of ready made Strings and then take advantage of my Fraction class's toString method to see if this works as expected. If it does, then use it in my main program. To me, that's the beauty of programming: we have this powerful and wonderful lab all to ourselves where we can create and experiment to our heart's content.

Good luck!
• 04-06-2010, 12:36 AM
Your tough love is working! haha

I tested it with a pre-ready string and got it to work. If I have anymore questions I shall be sure to post them here. Hopefully I won't need to though :p
• 04-06-2010, 01:12 AM
Alrighty, I have a question that is worth asking I believe. Heres my two classes.

Code:

```import java.util.Scanner; public class RunCalc {         public static void main(String[] args)         {                 String choice = "";                 String userFract = "0";                 String userFract2 = "0";                 Scanner scan = new Scanner(System.in);                 String fract;                 int clearCounter = 0;                                 String add = "a"; String multiply = "m";                 String subtract = "s"; String divide = "d";                 String reciprocal = "r"; String clear = "c";                 String reverse = "n"; String proper = "p";                 String improper = "i"; String quit = "q";                                                                 while(!choice.equals("q"))                 {                         if(clearCounter == 0)                         {                                 System.out.print("Enter a fraction: ");                                 userFract = scan.nextLine();                                 clearCounter++;                         }                                                 Fraction currentFract = Fraction.parseFraction(userFract);                         fract = currentFract.toString();                         System.out.println(fract);                                                 System.out.println("add:        a,  clear:            c");                         System.out.println("subtract:    s,  reverse sign:    n");                         System.out.println("multiply:    m,  proper display:  p");                         System.out.println("divide:      d,  improper display: i");                         System.out.println("reciprocal:  r,  quit:            q");                         System.out.print("-->");                         choice = scan.next();                         System.out.println("");                                                 if(choice.equals(add))                         {                                 System.out.print("Enter another fraction: ");                                 userFract2 = scan.nextLine();                                 Fraction newFract = Fraction.parseFraction(userFract2);                                                                 currentFract = currentFract.add(newFract);                                 fract = currentFract.toString();                         }                                                 if(choice.equals(clear))                         {                                 clearCounter--;                         }                                                                                 }         } }```
Code:

```public class Fraction {         int numerator;         int denominator;                 public Fraction(int num, int den)         {                 numerator = num;                 denominator = den;         }                 public Fraction()         {                 numerator = 0;                 denominator = 1;         }                         public int getNum()         {                 return numerator;         }                 public void setNum(int num)         {                 numerator = num;         }                 public int getDen()         {                 return denominator;         }                 public void setDen(int den)         {                 denominator = den;         }                 /*GCD calculator for simplifying fractions*/         public static int calcGCD(int a, int b)  //method header for calculating the GCD     {         if (a == 0 || b ==0)                   {                                   b = 0;                                 return b;                   }         if (a < b)  //if header to switch number order in case the first number is smaller than the second                   {                   /*Switching a and b*/             int t = a;              a = b;             b = t;                   /*End switch*/         }         int r = a % b;  //setting r to be the remainder of a divided by b         if (r == 0)  //if header                   {             return b;  //returning the value of b as the GCD         }                   else  //else header                   {             return calcGCD(b, r);  //returning the GCD         }     }                               /*   This method takes a String representation of a (proper or improper)   fraction and returns a corresponding instance of Fraction.  If the   String is invalid null is returned.     */ public static Fraction parseFraction(String input) {   boolean negative = input.charAt(0) == '-';    // negative value?   int numberStartIndex = (negative ? 1 : 0);    // beginning of digits   int spaceIndex = input.indexOf(' ');    // separates whole and frac parts   int slashIndex = input.indexOf('/');   int intPart = 0;                        // whole number part of the input   if (slashIndex == -1)      // input is a whole number   {       try       {         // read input as a whole number: no fraction part         intPart = Integer.parseInt(input.substring(numberStartIndex));         if (negative)             intPart = -intPart;          // correct for sign       }       catch (NumberFormatException e)       {         return null;       }       return new Fraction(intPart, 1);  // whole number   }   int fractionStart = 0;      // where the fraction starts in input   if (spaceIndex != -1)        // input is a whole number and a fraction   {       // read whole number part       fractionStart = spaceIndex + 1;  // fraction part starts here       try       {         intPart =           Integer.parseInt(input.substring(numberStartIndex, spaceIndex));       }       catch (NumberFormatException e)       {         return null;       }   }   // read the fraction part   int num, denom;   try   {       // read numerator       if (input.charAt(fractionStart) == '-')         fractionStart++;      // may have '-' if not a mixes fraction       num = Integer.parseInt(input.substring(fractionStart, slashIndex));   }   catch (NumberFormatException e)   {       return null;   }   try   {       // read denominator       denom = Integer.parseInt(input.substring(slashIndex + 1));   }   catch (NumberFormatException e)   {       return null;   }   int numerator = intPart*denom + num;      // total numerator   if (negative)       numerator = -numerator;                // correct sign if necessary   return new Fraction(numerator, denom); }                               public Fraction add(Fraction secondFract)           {                           int num1 = getNum();                         int den1 = getDen();                         int num2 = secondFract.getNum();                         int den2 = secondFract.getDen();                         int gcdTemp = 0;                                                 int newNum = (num1 * den2) + (num2 * den1);                         int newDen = (den1* den2);                                                   gcdTemp = calcGCD(newNum, newDen);                         newNum = newNum / gcdTemp;                         newDen = newDen / gcdTemp;                                                   return new Fraction(newNum, newDen);           }                             public String toString()         {                                 return numerator + "/" + denominator;         } }```
When I try to use the add function I get this error:
Code:

```Enter a fraction: 1/2 1/2 add:        a,  clear:            c subtract:    s,  reverse sign:    n multiply:    m,  proper display:  p divide:      d,  improper display: i reciprocal:  r,  quit:            q -->a Enter another fraction: Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0         at java.lang.String.charAt(String.java:686)         at Fraction.parseFraction(Fraction.java:77)         at RunCalc.main(RunCalc.java:48)```
Sorry for the long post! I honestly am a bit clueless as to why this is happening. Thanks!
• 04-06-2010, 02:05 AM
Fubarable
I'm on call and at work and thus not able to compile your code, but on a quick review of your code, this bit bugs me:
Code:

```                        choice = scan.next();  // #1                         System.out.println("");                                                 if(choice.equals(add))                         {                                 System.out.print("Enter another fraction: ");                                 userFract2 = scan.nextLine(); // #2                                 Fraction newFract = Fraction.parseFraction(userFract2);                                                                 currentFract = currentFract.add(newFract);                                 fract = currentFract.toString();                         }```
At the line at comment #1 you obtain the next token from the Scanner object with the next() method, but don't get the end of line token (via the nextLine() method). Then later at the line at comment #2 you call scan.nextLine() which likely gets the end of line token and nothing else. Then you try to parse this and it doesn't work. I suggest that you try changing #1 to

Code:

`choice = scan.nextLine(); // gets both "a" and the end of line tokens`
and see what happens.

Much luck!
• 04-06-2010, 05:06 AM
I appreciate the help! That fixed that error in a jiffy. The only problem that I have now is that its not displaying the new fraction that is the sum of the 2 fractions when I use the add function.

Either 1 - My addition method is flawed.
2 - My main method section for adding is flawed.

I shall investigate and post again if anything else arises. Thanks again for all the help, I am learning this very well right now.
• 04-06-2010, 06:18 PM
New question for you guys...

I am trying to make my toString method be able to read if the fraction is 0 or a negative so that it returns a negative or 0.

ie. "0" instead of "0/1" etc...

Heres my code for the method, it doesn't compile right now. I guess I need help in reading the index positions to tell if it is negative or 0...

Code:

```        public String toString()         {                 boolean negative = charAt(0) == '-';                 boolean zero = charAt(0) == '0';                 boolean negZero = charAt(0) == '-' && charAt(1) == '0';                 if(zero)                 {                         return "0";                 }                                 if(negZero)                 {                         return "0";                 }                                 if(negative)                 {                         return -numerator + "/" + denominator;                 }                 else                 {                         return numerator + "/" + denominator;                 }         }```
Any help is appreciated! Am I on the right track by trying to read index positions with charAt(#)?
• 04-06-2010, 11:17 PM
Fubarable
What object are you calling charAt(..) on? It can't be just called by itself but needs to be called on some String.
• 04-08-2010, 05:31 PM
Almost done now...
Edit: Problem solved. The program is working 100%. Thanks for all the help!
• 04-08-2010, 09:34 PM
Fubarable
Quote: