Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

public static double convertWeight(String value, String value2) {
    double lbs = 0;
    double ounces = 0;
    if (!value.equals("")) {
        lbs = Double.parseDouble(value);
    }
    if (!value2.equals("")) {
        ounces = Double.parseDouble(value2) * 0.062500;
    }
    double grams = (lbs + ounces) / 0.0022046;
    return grams;
}

I have this piece of code, where at sometimes i get pounds or oz value empty. The above piece of code works fine, but i am not happy the way i have written the code. Can anyone tell me a better alternate way.

I have to convertWeight. So from my service i get sometimes values or sometimes just empty strings. If its empty i ensure that i pass lbs or ounces "Zero" converWeight(value1, value2);

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
145 views
Welcome To Ask or Share your Answers For Others

1 Answer

Java 6 implemented a new String method, isEmpty(). As long as you're running 6 or above, you can rewrite your code using this method. It's a bit more readable.

try {
    if (!isEmpty(value)) {
        lbs = Double.parseDouble(value);
    }
    if (!isEmpty(value2)) {
        ounces = Double.parseDouble(value2) * 0.062500;
    }
} catch (NumberFormatException nfe) {
    //Do some notification
    System.err.println("Invalid input.");
}

As an added suggestion .. You may want to wrap this code in a try/catch block. If you don't, your program will crash with an uncaught exception if it tries to parse anything other than a valid double for either values.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...