1

考虑下面的 java 中的示例代码,它想要搜索操作中允许的任务

public boolean acceptableTaskForAction(String taskName,String actionName) {


    String[] allowedActions;
    switch (taskName){
    case "Payment" :
        allowedActions = { "full-payment", "bill-payment"};

    case "Transfer" :
        allowedActions = { "transfer-to-other", "tarnsfer-to-own"};

    }

    for (String action : allowedActions){
        if (actionName.equals(action)){
            return true;
            }
    }
    return false;
}

如您所知,上述内容不会编译为Array constants can only be used in initializers

我想定义不同的参数,所以它将是

public boolean acceptableTaskForAction(String taskName,String actionName) {


    String[] allowedActionsForPayment= { "full-payment", "payment"};
    String[] allowedActionsForTransfer= { "transfer-to-other", "tarnsfer-to-own"};
    String[] allowedActions={};
    switch (taskName){
    case "Payment" :
        allowedActions = allowedActionsForPayment;

    case "Transfer" :
        allowedActions = allowedActionsForTransfer;

    }

    for (String action : allowedActions){
        if (actionName.equals(action)){
            return true;
            }
    }
    return false;
}

你有没有想过其他的解决方案!?你认为最好的解决方案是什么?

4

2 回答 2

4

你可以做这样的事情你的情况

String[] allowedActions;
switch (taskName){
case "Payment" :
    allowedActions = new String[] { "full-payment", "bill-payment"};
    break;
case "Transfer" :
    allowedActions = new String[] { "transfer-to-other", "tarnsfer-to-own"};
    break;
}

数组常量只能在初始化器中使用,但您总是可以创建一个新String[]的并在需要时分配它。

于 2013-11-11T06:06:58.130 回答
1

而不是Array您可以ArrayList安全地使用您的要求!

List<String> allowedActions = new ArrayList<String>();
switch (taskName){
    case "Payment" :
        allowedActions.add("full-payment");
        allowedActions.add("payment");
        break;
    case "Transfer" :
        allowedActions.add("transfer-to-other");
        allowedActions.add("tarnsfer-to-own");
        break;
    }
return allowedActions.contains(actionName);
于 2013-11-11T06:07:20.707 回答