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);
}
}
添加回答
舉報