gpt4 book ai didi

java - Java中的数组常量初始化

转载 作者:行者123 更新时间:2023-11-29 07:52:49 27 4
gpt4 key购买 nike

考虑下面的 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;
}

如你所知,上面的代码不会编译为数组常量只能在初始化器中使用

我想过定义不同的参数,这样就可以了

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;
}

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

最佳答案

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

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[] 并在需要时分配它。

关于java - Java中的数组常量初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19899869/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com