+ 4

Java fractions

So I am making a method for adding fractions, but the user input begins as such: String frac1 = “5/6”; String frac2 = “1/7”; String frac3 = “-2/9”; How can I get java to read the String and interpret it as 2 seperate int variables (numerator, denominator)? I’m assuming parsing but I’m totally boggled how to break up the string and especially how to interpret negative values for calculating 2 fractions’ sum

18th Jul 2018, 10:56 PM
Jeff
Jeff - avatar
3 Antworten
+ 4
You can use String.split for get numerator and denominator of fraction then use Integer.valueOf (or Integer.parseInt) for detect if either are valid numbers and get their values like integer
18th Jul 2018, 11:13 PM
KrOW
KrOW - avatar
+ 3
Ues regex to split the input to nom/denom
19th Jul 2018, 7:51 AM
Haris
Haris - avatar
+ 2
Thanks guys, so very helpful!
19th Jul 2018, 10:49 AM
Jeff
Jeff - avatar