[英]Java switch : case expressions must be constant expressions
I have problem with the java switch im my school project: in code all constants in cases are underlined red and throw that case error 我的学校项目中的java开关出现问题:在代码中,所有情况下的常量都用红色下划线标记并抛出该案例错误
private static final int TCP = Integer.parseInt(PropertiesComunicator.getData("tcp"));
private static final int HTTP = Integer.parseInt(PropertiesComunicator.getData("http"));
private static final int HTTPS = Integer.parseInt(PropertiesComunicator.getData("https"));
private static final int TELNET = Integer.parseInt(PropertiesComunicator.getData("telnet"));
private static final int SSH = Integer.parseInt(PropertiesComunicator.getData("ssh"));
private static final int FTP_DATA = Integer.parseInt(PropertiesComunicator.getData("ftp-data"));
private static final int FTP_CONTROL = Integer.parseInt(PropertiesComunicator.getData("ftp-control"));
switch (portNumbers[i]) {
case HTTP:
portNames[i] = "http";
break;
case HTTPS:
portNames[i] = "https";
break;
case TELNET:
portNames[i] = "telnet";
break;
case SSH:
portNames[i] = "ssh";
break;
case FTP_DATA:
portNames[i] = "ftp-data";
break;
case FTP_CONTROL:
portNames[i] = "ftp-control";
break;
default:
portNames[i] = null;
break;
}
After a quick research on the internet i found that this error is because "case statements can only take compile-time constants, or enums" and my constant's values are taken from extern property file so i think this is the reason why this error occurs, but configuration of this constants by extern file is necessary condition for finishing my project :( Is there any solution except uncomfortable if-else recoding this part od source? 在互联网上进行快速研究后,我发现此错误是因为“ case语句只能使用编译时常量或枚举”,而我的常量值来自extern属性文件,因此我认为这是发生此错误的原因,但是通过extern文件配置此常数是完成我的项目的必要条件:(除了不舒服的if-else重新编码这部分od源以外,是否有其他解决方案?
PS these few ports aren't the only i have to analyze... PS这几个端口不是我唯一需要分析的...
gTypical approach here would be to use map/dictionary of some sort to map your input "keys" (in your case, portNumbers[i]
) to their "value" (eg map HTTP to "http"). g此处的典型方法是使用某种类型的map / dictionary将输入的“键”(在您的情况下为
portNumbers[i]
)映射到其“值”(例如,将HTTP映射到“ http”)。
You could do 你可以做
Map<Integer, String> protos = new HashMap<Integer, String>();
protos.put(HTTP, "http");
and solve everything by using 并通过使用解决所有问题
portNames[i] = protos.get(portNumber[i]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.