Search code examples
javaandroidif-statementis-empty

Android Studio If statement with || and && operator


I'm creating an application which updates users on the score of a football match either in real time or as a final result. At least one score must be inputted in order for the TextView to be updated and the relevant score to be displayed. I'm checking that at least 1 of a pair of EditText fields is not empty using the following code:

if(!(et_current.getText().toString().isEmpty())||(!(et_final.getText().toString().isEmpty()))
&& (!(et_current2.getText().toString().isEmpty())||(!(et_final2.getText().toString().isEmpty()))){
     if(!(et_final.getText().toString().isEmpty()))
              tv_final.setText(et_final.getText().toString());
     else
              tv_current.setText(et_current.getText().toString());

     if(!(et_final2.getText().toString().isEmpty()))
              tv_final2.setText(et_final2.getText().toString());
     else
              tv_current2.setText(et_current2.getText().toString());
}

I want to be able to set the correct TextView so I have another if statement inside the original if statement to see ensure the correct score is being updated.

When I run the code, I do not seem to be getting past the first if statement. Am I using the correct format or is there an better way to complete these checks?

Thanks!


Solution

  • For readabilities sake, get some variables going

        boolean currentEmpty = et_current.getText().toString().isEmpty();
        boolean current2Empty = et_current2.getText().toString().isEmpty();
        boolean finalEmpty = et_final.getText().toString().isEmpty();
        boolean final2Empty = et_final2.getText().toString().isEmpty();
    

    And then your code can be much cleaner. Something like

        if( (!currentEmpty || !finalEmpty) || (!current2Empty || !final2Empty)) {
    
            if(finalEmpty) {
                tv_current.setText(et_current.getText());
            }
            else {
                tv_final.setText(et_final.getText());
            }
    
            if(final2Empty) {
                tv_current2.setText(et_current2.getText());
            }
            else {
                tv_final2.setText(et_final2.getText());
            }
        }
    

    I'm not sure if that is completely correct as the requirement is not entirely clear to me, but it should atleast be a good start to follow what's going on.