![](/img/trans.png)
[英]all of the condition are working except on the second else-if statement, how to correct this?
[英]if else-if not working
我有一個 if else-if 塊,如下所示,但它只能在中途工作。if 部分有效,第一個 if-else 也是如此。 但是最后兩個 if-else 語句永遠不會被執行,即使在它們應該評估為真的情況下也是如此。 有人可以告訴我我在這里做錯了什么嗎?
//Getting current date and time
Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
//Getting user-entered date and time values.
String[] selected_date_string = date.getText().toString().split("-");
int selected_month = Integer.parseInt(selected_date_string[0]);
int selected_day = Integer.parseInt(selected_date_string[1]);
int selected_year = Integer.parseInt(selected_date_string[2]);
String[] selected_time_string = time.getText().toString().split(":");
int selected_hour = Integer.parseInt(selected_time_string[0]);
int selected_minute = Integer.parseInt(selected_time_string[1]);
boolean has_error = false;
int error = -1;
//PROBLEM AREA
if (selected_year < year) {
error = 1;
} else if ((selected_year == year) && (selected_month < month)) {
error = 2;
} else if ((selected_year == year) && (selected_month == month)) {//this part doesnt work no matter what I do!
error = 3;
} else if ((selected_year == year) && (selected_month == month) && (selected_day == day)) //this part too!
if (selected_hour < hour)
error = 4;
提前致謝!
通常我們會忘記Calendar
中的MONTH
是從零開始的,換句話說:一月的值是0
而不是1
,正如我們所期望的那樣。
您可能需要減少您的selected_month
...
在您的代碼中使用這一行:
int selected_month = Integer.parseInt(selected_date_string[0]) - 1;
你有一個重復的聲明:
else if ((selected_year == year) && (selected_month == month))
最后一個永遠不會被評估,因為前一個已經把它撿起來了。 我知道第二個更具體,但這並不重要。 例如,如果您的年份匹配並且您的月份匹配,那么您的日子也沒有關系,因為第一個變為真的語句是您的error = 3
else if 語句。
至於為什么最后兩個語句都沒有得到評估,我相信@Andreas_D 在提到月份是從零開始的值時就在上面。 可能是該語句有效,只是與您預期的不同。
Java 中的日歷 class 返回月份的 0-11,
所以如果當前月份是 Jan 那么它返回 0
對於 2 月 1 日,依此類推,
對於 12 月,它返回 11
所以你的 if 條件永遠不會等於任何方式
核實
如果有任何問題,請發表評論或回復
您應該將最具體的條件作為第一個 if。 最后一個 if 無法執行,因為它的條件比第三個( (selected_year == year) && (selected_month == month) )更具體,但第一部分在最后一個被檢查之前為第三個返回 true,所以即使最后一部分( selected_day == day )是真的,你也永遠不會得到最后一個 if 執行。
將該條件作為第一個條件將確保它會被檢查。
嘗試這個。
int month = c.get(Calendar.MONTH)+1;
我會改用switch case
構造。
當我執行這段代碼時:
Calendar c = Calendar.getInstance();
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
結果:
day = 28
month = 5
year = 2011
hour = 15
minute = 24
所以也許你在 2011 年 6 月 28 日通過測試它並沒有得到正確的比較,所以如果我在最后打印出錯誤 "07-11-2011" 和 "18:00" 它打印 -1
當我將它與“05-11-2011”一起使用時,它會打印 3
我的建議是改變
int month = c.get(Calendar.MONTH);
至
int month = c.get(Calendar.MONTH)+1;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.