WhiteGlove:
私は学校のためのアプリに取り組んでいます。私はコードを見て、私が作ったこの事を発見しました。
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;
}
この「ロジック」の背後にある考え方は、そこにアプリに書き込むための4つのスロットがあるが、どれも空にすることはできませんということです。そのうちの一つが空の場合、infoStatusという名前のTextViewが発生しました例外についてのメッセージが表示されます。
私は、これはリファクタリングを持つことができ、より少ない行で行うことができます知っているが、私はわからない方法です。これまでのところ私の考えでは、このでした:
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;
}
私はanswerTxt#は空となっているユーザーのための特定のメッセージを取得することはできません。
アービンド・クマールのAvinash:
君はそれを行うことができます
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;
}
}