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

I have some code like this:

class Foo {
    public double x;
}

void test() {
    Foo foo = new Foo();

    // Is this a valid way to test for zero? 'x' hasn't been set to anything yet.
    if (foo.x == 0) {

    }

    foo.x = 0.0;

    // Will the same test be valid?
    if (foo.x == 0) {

    }
}

I basically want to avoid a divide-by-zero exception in the future.

Thanks

See Question&Answers more detail:os

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

1 Answer

Numeric primitives in class scope are initialized to zero when not explicitly initialized.

Numeric primitives in local scope (variables in methods) must be explicitly initialized.

If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.

if(value != 0)
    //divide by value is safe when value is not exactly zero.

Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.

public boolean isZero(double value, double threshold){
    return value >= -threshold && value <= threshold;
}

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