# Thread: Fraction Calculator need help

1. Member
Join Date
Apr 2010
Posts
15
Rep Power
0

## 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!

2. Member
Join Date
Apr 2010
Posts
15
Rep Power
0
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!

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:
Java 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.

4. Member
Join Date
Apr 2010
Posts
15
Rep Power
0
True, I guess I needed reassurance. So to create a instance of fraction to be displayed I would do something like this?

Java 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);```

5. 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!

6. Member
Join Date
Apr 2010
Posts
15
Rep Power
0
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

7. Member
Join Date
Apr 2010
Posts
15
Rep Power
0
Alrighty, I have a question that is worth asking I believe. Heres my two classes.

Java 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("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("");

{
System.out.print("Enter another fraction: ");
userFract2 = scan.nextLine();
Fraction newFract = Fraction.parseFraction(userFract2);

fract = currentFract.toString();
}

if(choice.equals(clear))
{
clearCounter--;
}

}
}
}```
Java 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
}
{
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
{
fractionStart = spaceIndex + 1;  // fraction part starts here
try
{
intPart =
Integer.parseInt(input.substring(numberStartIndex, spaceIndex));
}
catch (NumberFormatException e)
{
return null;
}
}
int num, denom;
try
{
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
{
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);
}

{
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:
Java Code:
```Enter a fraction: 1/2
1/2
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!

8. 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:
Java Code:
```			choice = scan.next();  // #1
System.out.println("");

{
System.out.print("Enter another fraction: ");
userFract2 = scan.nextLine(); // #2
Fraction newFract = Fraction.parseFraction(userFract2);

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

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

Much luck!

9. Member
Join Date
Apr 2010
Posts
15
Rep Power
0
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.

10. Member
Join Date
Apr 2010
Posts
15
Rep Power
0
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...

Java 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(#)?

11. What object are you calling charAt(..) on? It can't be just called by itself but needs to be called on some String.

12. Member
Join Date
Apr 2010
Posts
15
Rep Power
0

## Almost done now...

Edit: Problem solved. The program is working 100%. Thanks for all the help!
Last edited by askinne2; 04-08-2010 at 07:30 PM.

Edit: Problem solved. The program is working 100%. Thanks for all the help!
You're welcome and congrats! I look forward to seeing you back here either asking questions or better, answering them.