I have a branch which replace system day of week integer value to human readable string value.
When I use if-else statement like the following, 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 switch-case statement like the following, it warns the value getResources().getString(R.string.sunday) assigned to curStrDayOfWeek is never used. Then I got 6 warnings since value have 7 branch.
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'd like to code without warning (Except typo). How can I use switch-case statement without warning?
But if I try to use switch-case statement like the following, it warns the value
getResources().getString(R.string.sunday)
assigned tocurStrDayOfWeek
is never used.
And it's absolutely right - because you'd immediately fall through to the next branch. You need a break
statement:
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;
...
}
Personally I'd probably just build an array though:
private static final int[] DAY_NAME_RESOURCES = {
0, // not used
R.string.sunday,
R.string.monday,
R.string.tuesday,
...
};
Then use:
curStrDayOfWeek = getResource().getString(DAY_NAME_RESOURCES[i]);
See more on this question at Stackoverflow