Advertisement
pro-themes

Fraction Calculator

Jun 13th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.74 KB | None | 0 0
  1. /**
  2.  * Jessica Wong
  3.  *
  4.  */
  5.  
  6. import java.util.*;
  7. public class Main
  8. {
  9.     public static void main(String[] args)
  10.     {
  11.      
  12.         Scanner scan = new Scanner(System.in);
  13.         String input = "";
  14.         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.");
  15.         while (!input.equalsIgnoreCase("quit"))
  16.         {
  17.             input = scan.next();
  18.             if (!input.equalsIgnoreCase("quit"))
  19.             {
  20.                 System.out.println(input + " as a fraction is: " + convertToFraction(input));
  21.             }
  22.         }
  23.     }
  24.     public static int getNumerator(String fraction)
  25.     {
  26.         String numerator;
  27.         if (fraction.indexOf('_') != -1)
  28.         {
  29.             numerator = fraction.substring(fraction.indexOf('_') + 1,fraction.indexOf('/'));
  30.             String wholenum = fraction.substring(0,fraction.indexOf('_'));
  31.             return Integer.parseInt(numerator,10)+Integer.parseInt(wholenum,10)*getDenominator(fraction);
  32.         }
  33.         else if (fraction.indexOf('/') != -1)
  34.         {
  35.             numerator = fraction.substring(0,fraction.indexOf('/'));
  36.             return Integer.parseInt(numerator,10);
  37.         }
  38.         else
  39.         {
  40.             return Integer.parseInt(fraction,10);
  41.         }
  42.     }
  43.     public static int getDenominator(String fraction)
  44.     {
  45.         if (fraction.indexOf('/') != -1)
  46.         {
  47.             String denominator = fraction.substring(fraction.indexOf('/') + 1, fraction.length());
  48.             return Integer.parseInt(denominator,10);
  49.         }
  50.         else
  51.         {
  52.             return 1;
  53.         }
  54.     }
  55.     public static String convertToFraction(String input)
  56.     {
  57.         if (input.indexOf('/') != -1)
  58.         {
  59.             return (getNumerator(input) + "/" + getDenominator(input));
  60.         }
  61.         else
  62.         {
  63.             return input;
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement