63350541
63350541

Reputation: 37

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?

Upvotes: 1

Views: 1491

Answers (3)

dreamcrash
dreamcrash

Reputation: 51413

The problem with your ternary attempts is that they are not corrected in terms of syntax:

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

For the Java language specification (§15.25):

15.25. Conditional Operator ? :

The conditional operator ? : uses the boolean value of one expression to decide which of two other expressions should be evaluated.

ConditionalExpression: ConditionalOrExpression ConditionalOrExpression ? Expression : ConditionalExpression

So in your case is a = (conditional expression) ? value of 'a' if conditional expression is true : value of 'a' if the conditional expression is false ;

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

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

Looks pretty fine, except one thing the way how you set avariable.

double a = <condition> ? <true> : <false>:

You can additionally use Apache utils to simplify a bit the code.

import org.apache.commons.lang3.StringUtils;

public double setA() {
    return StringUtils.isBlank(aField.getText()) ? 1 : Double.parseDouble(aField.getText());
}

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

Upvotes: 1

Suraj Gautam
Suraj Gautam

Reputation: 1590

Try this:

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

Upvotes: 1

Related Questions