简体   繁体   English

如果else陈述无法正常运作

[英]If else statement not functioning properly

af, ae, and be are all integers and here I am checking to see if they equal 0. If not, I want to return null. af,ae和be都是整数,在这里我检查它们是否等于0。如果不等于,我想返回null。 If they do equal zero, I want to return glorpPoly. 如果它们等于零,我想返回glorpPoly。 For some reason though, it always returns null even when the condition is satisfied... does anyone know why? 但是由于某种原因,即使条件满足,它也总是返回null。有人知道为什么吗? all these values are of a type our teacher created called MyDouble. 所有这些值都是我们的老师创建的MyDouble类型。 all of them have been initialized to this value, but it still doesn't work. 它们都已初始化为该值,但仍然不起作用。

MyDouble af = a.multiply(poly.c);
    MyDouble ae = a.multiply(poly.b);
    MyDouble bf = b.multiply(poly.c);
    MyDouble cf = c.multiply(poly.c);
    MyDouble be = b.multiply(poly.b);
    MyDouble ad = a.multiply(poly.a);
    MyDouble ce = c.multiply(poly.b);
    MyDouble bd = b.multiply(poly.c);
    MyDouble cd = c.multiply(poly.a);
    //Adding the the variables and creating new coefficients
    MyDouble newA = af;
    MyDouble newB = ae.add(bf);
    MyDouble newC = cf.add(be).add(ad);
    MyDouble newD = ce.add(bd);
    MyDouble newE = cd;
    MyDouble zero = new MyDouble(0)
if(af != zero && ae !=zero && be != zero){

        return null;
    }
    else{
        MartianPolynomial glorpPoly = new MartianPolynomial(newC,newD,newE);
        return glorpPoly;
    }
}

Objects can't be compared using == or != . 无法使用==!=比较对象。 You have to use the equals() method: 您必须使用equals()方法:

if (!af.equals(zero) && !ae.equals(zero) && !be.equals(zero) {
  ...
}

The operators != and ( == ) check for object identity, ie if both references point to the same instance. 运算符!=和( == )检查对象身份,即是否两个引用都指向同一实例。 They don't compare the "value" of the instances. 他们不比较实例的“值”。

LE: if 'af','ae' and 'be' are numbers (type int,double,float) you can use: LE:如果'af','ae'和'be'是数字(输入int,double,float),则可以使用:

if(af != 0 && ae !=0 && be != 0)

but if they are objects, you can either compare their attributes by 0 or compare them with an object of the same type.See: http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx 但是如果它们是对象,则可以将其属性按0进行比较,也可以将它们与相同类型的对象进行比较。请参阅: http : //msdn.microsoft.com/zh-cn/library/bsc2ak47.aspx

怎么样

if(! af.equals(zero) && ! ae.equals(zero) && ! be.equals(zero) ) ...

If you are checking if they are all zero, just multiply them all together and if the result is zero, well you know... 如果要检查它们是否全部为零,只需将它们全部相乘即可,如果结果为零,那么您知道...

I am assuming, since you did not provide your MyDouble class, that you have a method of retrieving the value ? 我假设,由于您没有提供MyDouble类,所以您有一种检索value的方法?

if ((af.value() * ae.value() * be.value()) != 0)

OP , please provide us with your MyDouble.java class. OP,请向我们提供您MyDouble.java类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM