0

fraction calculator

i need to make fraction calculator without using arrays and i am so lost. Right now I am trying to parse the fraction together using indexes and I need some help figuring out how to do that. this is what i have so far: package fracCalc; import java.util.Scanner; public class FracCalc { public static void main(String[] args){ // TODO: Read the input from the user and call produceAnswer with an equation Scanner console=new Scanner(System.in); System.out.println("Enter your Equation"); String equation = console.nextLine(); String fraction = produceAnswer(equation); System.out.println(fraction); } public static String produceAnswer(String input){ // TODO: Implement this function to produce the solution to the input Scanner parser = new Scanner(input); String fraction1 = parser.next(); String operator = parser.next(); String fraction2 =parser.next(); String whole1 = "0"; String whole2 = "0"; String numerator = ""; String denominator = ""; String Whole =""; String Fraction =""; if (fraction1.indexOf("_")!=-1){ whole1=fraction1.substring(0, fraction1.indexOf("_")); numerator=fraction1.substring(fraction1.indexOf("_"), fraction1.indexOf("/")); denominator=fraction1.substring(fraction1.indexOf("/")); } if (fraction2.indexOf("_")!=-1){ whole2=fraction2.substring(0, fraction2.indexOf("_")); numerator=fraction2.substring(fraction2.indexOf("_"), fraction2.indexOf("/")); denominator=fraction2.substring(fraction2.indexOf("/")); } Whole=whole1+whole2; Fraction=fraction1+fraction2; String Result[]= return result; //index: 01234567890 //frctn: w_n/d //w=whole, n=numerator, d=denominator //indexOf("_")=1, indexOf("/")=3 //using the index to define the numerator, denominator

15th Nov 2016, 4:54 PM
Jared Winfield
Jared Winfield - avatar
1 Antwort
+ 1
I would recommend using double values instead of String, or eventually parsing those Strings into double type. Double.parseDouble(parser.next()) - its the fastest solution for this. You can always use toString() method to get String value of numbers. ANOTHER... solution is to create your own Object "Fraction" and put into that nominator and denominator as its arguments.
15th Nov 2016, 5:34 PM
Maksym Zieliński
Maksym Zieliński - avatar