samedi 5 décembre 2020

Convert if/else to ternary operator Java

My function setA() looks like this:

public double setA(){
    double a;
    
    aField.getText() == null || aField.getText().trim().isEmpty() ? a = 1 : a = Double.parseDouble(aField.getText());

    //a = aField.getText() == null || aField.getText().trim().isEmpty() ? a = 1 : a = Double.parseDouble(aField.getText());

    //return aField.getText() == null || aField.getText().trim().isEmpty() ? a = 1 : a = Double.parseDouble(aField.getText());

    /*if(aField.getText() == null || aField.getText().trim().isEmpty())
        a = 1;
    else
       a = Double.parseDouble(aField.getText());*/
   
    return a;
}

I want to get rid of if/else and rewrite it with the ternary operator. None of these 3 ternary options work and, on a build, they show the same mistake:

java: unexpected type required: variable found: value

Meanwhile the commented if/else block works just fine. Passing TextField aField into the function and working through this. doesn't help + before building I see

Variable 'a' might not have been initialized

What's the mistake?

Aucun commentaire:

Enregistrer un commentaire