Leonne
Leonne

Reputation: 85

why is my ternary boolean operator showing the opposite

isnt the ternary operator suppose to work as arg ? true:false ??? so if duration and petroleum are more than the stated amount than field variables, it should return true.. but this returns false instead

public class test12 {
    int duration = 260;
    int petroleum = 300;
    boolean result;

    public void checktrain(){
        boolean result = duration>=250 && petroleum>=235? true : false;
        this.result = result;
    }

    public void run(){
        System.out.print(result);
    }

    public static void main(String args[]){
        test12 tr = new test12();
        tr.run();
    }
}

Upvotes: 0

Views: 208

Answers (2)

Suresh Atta
Suresh Atta

Reputation: 121998

You forgot to call checktrain().So as it remains with default value false of boolean.

Try to call that method.

public static void main(String args[]){
test12 tr = new test12();
tr.checktrian();
tr.run();
}

And check train method can be written simply as

public void checktrain(){
this.result= duration>=250 && petroleum>=235;
}

And even you can avoid that boolean by writing

  public boolean checktrain(){
    return  duration>=250 && petroleum>=235;
    }

Upvotes: 1

Juned Ahsan
Juned Ahsan

Reputation: 68715

Result is false because you have never called the method checktrain and default value of member variable result is false.

Upvotes: 5

Related Questions