如何修剪此代码?
prefsDisplay = getSharedPreferences("spinnerSelection",
Context.MODE_PRIVATE);
prefsPlan = getSharedPreferences("spinnerSelection1",
Context.MODE_PRIVATE);
if (prefsDisplay.getInt("spinnerSelection", 0) == 0) {
s1 = 0;
} else if (prefsDisplay.getInt("spinnerSelection", 0) == 1) {
s1 = 1;
} else if (prefsDisplay.getInt("spinnerSelection", 0) == 2) {
s1 = 2;
} else if (prefsDisplay.getInt("spinnerSelection", 0) == 3) {
s1 = 3;
} else {
s1 = 0;
DP.BreakdownMonths = 0;
}
if (prefsPlan.getInt("spinnerSelection1", 0) == 0) {
s2 = 0;
} else if (prefsPlan.getInt("spinnerSelection1", 0) == 1) {
s2 = 1;
} else if (prefsPlan.getInt("spinnerSelection1", 0) == 2) {
s2 = 2;
} else {
s2 = 0;
DP.PlanType = "highint";
}
基本上,我正在做什么,当应用程序登录时,我希望它检查SharedPreferences。如果找到一个值,它会分配一个值,否则,它默认为一个值。
答案 0 :(得分:3)
以下内容与您的代码完全相同。使用分配给共享首选项的值,如果为空,则分配0并分配DP。
prefsDisplay = getSharedPreferences("spinnerSelection",
Context.MODE_PRIVATE);
prefsPlan = getSharedPreferences("spinnerSelection1",
Context.MODE_PRIVATE);
s1 = prefsDisplay.getInt("spinnerSelection", -1 );
if( s1 < 0 ) {
s1 = 0;
DP.BreakdownMonths = 0;
}
s2 = prefsPlan.getInt("spinnerSelection1", -1 );
if( s2 < 0 ) {
s2 = 0;
DP.PlanType = "highint";
}
答案 1 :(得分:1)
使用switch
和case
定义相应的if语句,并使用default
分配它是否与任何if语句都匹配。
示例:
int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);