Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Jessica Wong
- *
- */
- import java.util.*;
- public class Main
- {
- public static void main(String[] args)
- {
- Scanner scan = new Scanner(System.in);
- String input = "";
- System.out.println("Enter a string to be converted into a fraction. Ex. 2_3/5 is the same as saying 2 3/5 | Type 'quit' in order to stop the program.");
- while (!input.equalsIgnoreCase("quit"))
- {
- input = scan.next();
- if (!input.equalsIgnoreCase("quit"))
- {
- System.out.println(input + " as a fraction is: " + convertToFraction(input));
- }
- }
- }
- public static int getNumerator(String fraction)
- {
- String numerator;
- if (fraction.indexOf('_') != -1)
- {
- numerator = fraction.substring(fraction.indexOf('_') + 1,fraction.indexOf('/'));
- String wholenum = fraction.substring(0,fraction.indexOf('_'));
- return Integer.parseInt(numerator,10)+Integer.parseInt(wholenum,10)*getDenominator(fraction);
- }
- else if (fraction.indexOf('/') != -1)
- {
- numerator = fraction.substring(0,fraction.indexOf('/'));
- return Integer.parseInt(numerator,10);
- }
- else
- {
- return Integer.parseInt(fraction,10);
- }
- }
- public static int getDenominator(String fraction)
- {
- if (fraction.indexOf('/') != -1)
- {
- String denominator = fraction.substring(fraction.indexOf('/') + 1, fraction.length());
- return Integer.parseInt(denominator,10);
- }
- else
- {
- return 1;
- }
- }
- public static String convertToFraction(String input)
- {
- if (input.indexOf('/') != -1)
- {
- return (getNumerator(input) + "/" + getDenominator(input));
- }
- else
- {
- return input;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement