Search code examples
javamethodsfractions

Java method to accept mixed number fraction and return a double


I need help getting this method to accept a mixed number e.g. (2 1/2) stored as one variable instead of two. Currently I have int and frac which come from two separate text fields.

public double convertFrac(int whole, String frac){
        if (frac == null || frac.equals(""))
            return whole;
        String[] parts = frac.split("/");
        return whole + (double)Integer.parseInt(parts[0]) / (double)Integer.parseInt(parts[1]);
    }

edited the code thanks to a suggestion from Bohemian.

it may be clunky by some of your standards, but I got it working =D

public static double convertFrac(String frac){
        String wholeStr, num, denom, fraction;
        int whole = 0;
        String[] parts = frac.split(" ");
        wholeStr = parts[0];
        whole = Integer.parseInt(wholeStr);

        if(parts.length == 1){
            return whole;
        }

        wholeStr = parts[0];
        whole = Integer.parseInt(parts[0]);
        fraction = parts[1];
        String[] fracParts = fraction.split("/");
        num = fracParts[0];
        denom = fracParts[1];

        return whole + (double)Integer.parseInt(fracParts[0]) / (double)Integer.parseInt(fracParts[1]);
    }

Solution

  • This is bug #1:

    if(frac == ""){ // tests if frac is the same object as the blank constant
    

    You must use

    if(frac.equals("")){ // tests if fraq is blank
    


    This is bug #2:

    num = Integer.parseInt(frac); // will explode if frac is actually a fraction
    


    Instead of what you have, I would simplify it to this:

    public double convertFrac(int whole, String frac) {
        if (frac == null || frac.equals(""))
            return whole;
        String[] parts = frac.split("/");
        return whole + (double)Integer.parseInt(parts[0]) / (double)Integer.parseInt(parts[1]);
    }
    

    You should not consider frac having only one number, because it makes no sense. Either it's blank or it's a fraction.