/* This method takes a String representation of a (proper or improper) fraction and returns a corresponding instance of Fraction. If the String is invalid null is returned. */ public static Fraction parseFraction(String input) { boolean negative = input.charAt(0) == '-'; // negative value? int numberStartIndex = (negative ? 1 : 0); // beginning of digits int spaceIndex = input.indexOf(' '); // separates whole and frac parts int slashIndex = input.indexOf('/'); int intPart = 0; // whole number part of the input if (slashIndex == -1) // input is a whole number { try { // read input as a whole number: no fraction part intPart = Integer.parseInt(input.substring(numberStartIndex)); if (negative) intPart = -intPart; // correct for sign } catch (NumberFormatException e) { return null; } return new Fraction(intPart, 1); // whole number } int fractionStart = 0; // where the fraction starts in input if (spaceIndex != -1) // input is a whole number and a fraction { // read whole number part fractionStart = spaceIndex + 1; // fraction part starts here try { intPart = Integer.parseInt(input.substring(numberStartIndex, spaceIndex)); } catch (NumberFormatException e) { return null; } } // read the fraction part int num, denom; try { // read numerator if (input.charAt(fractionStart) == '-') fractionStart++; // may have '-' if not a mixes fraction num = Integer.parseInt(input.substring(fractionStart, slashIndex)); } catch (NumberFormatException e) { return null; } try { // read denominator denom = Integer.parseInt(input.substring(slashIndex + 1)); } catch (NumberFormatException e) { return null; } int numerator = intPart*denom + num; // total numerator if (negative) numerator = -numerator; // correct sign if necessary return new Fraction(numerator, denom); }