How could I refactor this bit of code here to achieve the same result?

WhiteGlove :

I am working on an app for school. I was looking through the code and found this thing I made:

if (answerTxt1.getText().toString().matches("")) {
        infoStatus.setText("Answer1 cannot be empty!");
        return;
   } else if (answerTxt2.getText().toString().matches("")){
        infoStatus.setText("Answer2 cannot be empty!");
        return;
   } else if (answerTxt3.getText().toString().matches("")){
        infoStatus.setText("Answer3 cannot be empty!");
        return;
   } else if (answerTxt4.getText().toString().matches("")){
       infoStatus.setText("Answer4 cannot be empty!");
       return;
    }

The idea behind this 'logic' is that there are 4 slots to write on the app but none can't be empty. If one of them is empty, a textView named infoStatus will display the message about the Exception ocurred.

I know this can have a refactor and can be done in less lines but I am not sure how. So far my idea was this:

if (answerTxt1.getText().toString().matches("") 
             || answerTxt2.getText().toString().matches("")
             || answerTxt3.getText().toString().matches("")
             || answerTxt4.getText().toString().matches("")) {

       infoStatus.setText("One of the answers is empty!");
       return;
    }

but I won't get the specific message for the user of which answerTxt# is empty.

Arvind Kumar Avinash :

You can do it as

TextView[] textViews = {answerTxt1, answerTxt2, answerTxt3, answerTxt1};
for(int i=0; i<textViews.length; i++){
    if(textViews[i].getText().toString().isEmpty()){
        infoStatus.setText("Answer"+ (i+1) + " cannot be empty!");
        break;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=393867&siteId=1
Recommended