3 回答
TA贡献1883条经验 获得超3个赞
就像您可以阅读此答案一样。:
当您编写多个 if 语句时,可能会有多个 if 语句被评估为 true,因为这些语句彼此独立。
当您编写单个 if else-if else-if ... else 语句时,只能将一个条件评估为 true(一旦找到评估为 true 的第一个条件,将跳过下一个 else-if 条件)。
因此,在您的示例中,在 method 之后startTwiceDailyNotification,变量hasSelected设置为 2。因此第二个“if 语句”被评估为 true,这就是startTwiceDailyNotification2调用 method 的原因。
要修复它,您应该使用“一个 if else-if else-if ... else 语句”,如下所示:
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
if (hasSelected == 1) {
startTwiceDailyNotification(calendar);
}
else if (hasSelected == 2) {
startTwiceDailyNotification2(calendar);
}
}
TA贡献1820条经验 获得超2个赞
hasSelected = 2;被标记这就是它出现的原因。hasselected =1单击按钮时首先设置。
试试这个方法:
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
if (hasSelected == 1) {
startTwiceDailyNotification(calendar);
} else
if (hasSelected == 2) {
startTwiceDailyNotification2(calendar);
}
}
TA贡献1799条经验 获得超9个赞
块内发现逻辑错误
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
if (hasSelected == 1) {
//At this point hasSelected is 1
startTwiceDailyNotification(calendar);
//At this point hasSelected is 2
}
//No **else** statement so the next if statement is also checked
//Use an else here to prevent this block from executing when previous is true
if (hasSelected == 2) {
//Next code executed also
startTwiceDailyNotification2(calendar);
}
}
添加回答
举报