Results 1 to 16 of 16
Thread: Fraction Calculator need help
 04062010, 12:08 AM #1Member
 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!

There's a link on the assignment page which gives you a parse method. If it were me, I'd just use that.
 04062010, 12:44 AM #3Member
 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!

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.
 04062010, 01:08 AM #5Member
 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);

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!
 04062010, 01:36 AM #7Member
 Join Date
 Apr 2010
 Posts
 15
 Rep Power
 0
Your tough love is working! haha
I tested it with a preready 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
 04062010, 02:12 AM #8Member
 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("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; } } } }
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 } 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; } }
Java 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)

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(""); 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(); }
Java Code:choice = scan.nextLine(); // gets both "a" and the end of line tokens
Much luck!
 04062010, 06:06 AM #10Member
 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.
 04062010, 07:18 PM #11Member
 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; } }

What object are you calling charAt(..) on? It can't be just called by itself but needs to be called on some String.
 04082010, 06:31 PM #13Member
 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; 04082010 at 08:30 PM.


Re: Fraction Calculator need help
Reawakened zombie post deleted. thread locked.

Re: Almost done now...
@shunix123: If you have a question, then post your code and ask your question in a new thread. Please don't ask for code hand outs as though. Your work should be yours and yours alone.
Similar Threads

Mixed Fraction
By x3iancute in forum NetBeansReplies: 2Last Post: 01192010, 04:15 PM 
Fraction Problem
By Jakora33 in forum New To JavaReplies: 6Last Post: 09162009, 04:51 PM 
Need help on Fraction
By mitch25 in forum New To JavaReplies: 2Last Post: 07242009, 10:46 PM 
(Help) Fraction Summation and Exponents
By SapphireSpark in forum New To JavaReplies: 19Last Post: 10092008, 05:01 AM 
Big Fraction 1.00
By JavaBean in forum Java SoftwareReplies: 1Last Post: 03262008, 05:24 AM
Bookmarks