有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何重构这段代码以获得相同的结果?

我正在为学校开发一个应用程序。我在查看代码时发现了我制作的东西:

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的文本视图将显示有关发生异常的消息

我知道这可以有一个重构,可以在较少的行中完成,但我不知道如何。到目前为止,我的想法是:

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#为空的用户的特定消息


共 (2) 个答案

  1. # 1 楼答案

    你可以照我说的做

    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;
        }
    }
    
  2. # 2 楼答案

    如果定义一个方法来检查任意文本视图是否为空,如果为空,则设置错误字段,如下所示:

    boolean checkEmpty(TextView textView, String name) {
       if (textView.getText().length() == 0) {
            infoStatus.setText(name + " cannot be empty!");
            return true;
       }
       return false;
    }
    

    然后,您可以消除代码中的大部分重复:

    if (checkEmpty(answerTxt1, "answerTxt1")) {
        return;
    }
    if (checkEmpty(answerTxt2, "answerTxt2")) {
        return;
    }
    ...
    

    您甚至可以通过创建数据结构来保存文本视图和错误消息,但这样做的代价是使代码更加复杂、僵化和脆弱