带有switch case语句的Android Studio 1.1警告

时间:2015-04-26 12:17:19

标签: java android android-studio

我有一个分支,它将系统星期几整数值替换为人类可读的字符串值。

当我使用if-else语句时,Android Studio 1.1不会发出任何警告。

int intDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
String curStrDayOfWeek = "";
if (intDayOfWeek == 1) {
    curStrDayOfWeek = getResources().getString(R.string.sunday);
}
else if(intDayOfWeek == 2) {
    curStrDayOfWeek = getResources().getString(R.string.monday);
}
else if(intDayOfWeek == 3) {
    curStrDayOfWeek = getResources().getString(R.string.tuesday);
}
[SNIP]

globals = (Globals) this.getApplication();

try {
    [SNIP]
    globals.hdsr_data.put("currentDayOfWeek", curStrDayOfWeek);
    [SNIP]
catch (Exception e) {
        System.out.println("Error:" + e);
    }
   [SNIP]

但是如果我尝试使用如下所示的switch-case语句,它会警告值getResources()。从不使用分配给curStrDayOfWeek的getString(R.string.sunday)。然后我得到了6个警告,因为值有7个分支。

int intDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
switch (intDayOfWeek) {
    case 1 : curStrDayOfWeek = getResources().getString(R.string.sunday);
    case 2 : curStrDayOfWeek = getResources().getString(R.string.monday);
    case 3 : curStrDayOfWeek = getResources().getString(R.string.tuesday);
[SNIP]
}

我想在没有警告的情况下编码(除了拼写错误)。如何在没有警告的情况下使用switch-case语句?

1 个答案:

答案 0 :(得分:6)

  

但是,如果我尝试使用如下所示的switch-case语句,则会警告从未使用分配给getResources().getString(R.string.sunday)的值curStrDayOfWeek

这是绝对正确的 - 因为你会立即进入下一个分支。您需要break声明:

switch (intDayOfWeek) {
    case 1:
        curStrDayOfWeek = getResources().getString(R.string.sunday);
        break;
    case 2:
        curStrDayOfWeek = getResources().getString(R.string.monday);
        break;
    case 3:
        curStrDayOfWeek = getResources().getString(R.string.tuesday);
        break;
    ...
}

我个人可能只是建立一个数组:

private static final int[] DAY_NAME_RESOURCES = {
    0, // not used
    R.string.sunday,
    R.string.monday,
    R.string.tuesday,
    ...
};

然后使用:

curStrDayOfWeek = getResource().getString(DAY_NAME_RESOURCES[i]);