How do i read fractions off a string input in java i want th
How do i read fractions off a string input in java?
i want the user to input a string of fractions say
\"13/3 3/2 3/8 12/5 4/5\"
i want to read these fractions and store them into an array int if possible, and get the total count of fractions inputed.
in this case count = 5
array[0] = 13/3
or array[0] =13 array[1]=/ array[2] =3
i\'m not sure.. i\'m kinda lost..
please show me in code
thank you for the help!!
Solution
Hi, Please find my implemetation.
Please let me know in case of any issue.
public class Test {
public static void main(String[] args) {
// Hi you can take all inout in a line as String
// and you can split input by space character (\' \')
// and after that each individual entery: adain you can divide by \'/\' character
String input = \"13/3 3/2 3/8 12/5 4/5\";
String[] fractionsStr = input.split(\"\\\\s+\"); // split by space
// now create numerator and denominator array of length fractionsStr
int num_of_fraction = fractionsStr.length;
int numerators[] = new int[num_of_fraction];
int denominators[] = new int[num_of_fraction];
// now iterate through fractionsStr and store numertors and denominators
for(int i=0; i<num_of_fraction; i++){
String fraction = fractionsStr[i];
// split fraction by \'/\'
String[] fractionT = fraction.split(\"/\");
numerators[i] = Integer.parseInt(fractionT[0]);
denominators[i] = Integer.parseInt(fractionT[1]);
}
//printing fraction
for(int i= 0; i<num_of_fraction; i++){
System.out.println(numerators[i]+\"/\"+denominators[i]);
}
}
}
/*
Output:
13/3
3/2
3/8
12/5
4/5
*/

