Android Studio 1.1 warning with case switch statement

I have a branch that replaces the system day of the week with an integer value with a human-readable string value.

When I use the if-else statement as shown below, Android Studio 1.1 does not warn anything.

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]

But if I try to use the switch-case statement as shown below, it warns the value of getResources (). getString (R.string.sunday) assigned by curStrDayOfWeek is never used. Then I received 6 warnings, since the value has 7 branches.

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

I would like to encode without warning (except for a typo). How can I use the switch-case statement without warning?

+4
source share
1

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]);
+6

Source: https://habr.com/ru/post/1584729/


All Articles