3 回答

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊
就像您可以閱讀此答案一樣。:
當(dāng)您編寫多個(gè) if 語句時(shí),可能會(huì)有多個(gè) if 語句被評(píng)估為 true,因?yàn)檫@些語句彼此獨(dú)立。
當(dāng)您編寫單個(gè) if else-if else-if ... else 語句時(shí),只能將一個(gè)條件評(píng)估為 true(一旦找到評(píng)估為 true 的第一個(gè)條件,將跳過下一個(gè) else-if 條件)。
因此,在您的示例中,在 method 之后startTwiceDailyNotification,變量hasSelected設(shè)置為 2。因此第二個(gè)“if 語句”被評(píng)估為 true,這就是startTwiceDailyNotification2調(diào)用 method 的原因。
要修復(fù)它,您應(yīng)該使用“一個(gè) 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貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超3個(gè)贊
hasSelected = 2;被標(biāo)記這就是它出現(xiàn)的原因。hasselected =1單擊按鈕時(shí)首先設(shè)置。
試試這個(gè)方法:
@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貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個(gè)贊
塊內(nèi)發(fā)現(xiàn)邏輯錯(cuò)誤
@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);
}
}
添加回答
舉報(bào)