Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - Checking for empty strings

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...