如何在 switch case 中使用字符串数组的输入?
String[] mon=new String[]{"January","February","March","April","May","June","July","August","September","October","November","December"};
switch (mon)
{
case "January":
m=1;
break;
case "February":
m=1;
break;
}
最佳答案
Java(版本 7 之前)不支持 switch
情况下的 String。但是您可以通过使用 enum
来获得所需的结果。
private enum Mon {
January,February,March,April,May,June,July,August,September,October,November,December
};
String value; // assume input
Mon mon = Mon.valueOf(value); // surround with try/catch
switch(mon) {
case January:
m=1;
break;
case February:
m2;
break;
// etc...
}
请参阅 here 了解更多信息