[英]how to make an if statement in switch case by not get the value of the another case?
現在我有一個問題,我想以此運行我的代碼,以便檢查案例2的februay(如果year為true),而不是運行execute if語句(如果為false),它將默認設置,但是現在轉到case 3語句如何解決不是轉到case 3而是轉到默認值的問題?
//這是我的代碼
public static void main(String[] args) {
getDaysInMonth(1, 2018);
System.out.println(getDaysInMonth(2, 2018));
}
public static boolean isLeapYear(int year) {
if(year < 1 && year > 9999) {
return false;
} else {
if(year % 4 == 0) {
return true;
} else if(year % 100 == 0) {
return false;
} else if(year % 400 == 0) {
return true;
} else {
return false;
}
}
}
public static int getDaysInMonth(int month, int year) {
if((month < 1 || month > 12) && (year < 1 || year > 9999)) {
return -1;
}
isLeapYear(year);
int days;
switch(month) {
case 1:
days = 31;
break;
case 2:
if(year == 1) {
days = 29;
break;
}
case 3:
days = 31;
break;
case 4:
days = 30;
break;
case 5:
days = 31;
break;
case 6:
days = 30;
break;
case 7:
days = 31;
break;
case 8:
days = 31;
break;
case 9:
days = 30;
break;
case 10:
days = 31;
break;
case 11:
days = 30;
break;
case 12:
days = 31;
break;
default:
days = 28;
break;
}
return days;
}
發生這種情況是因為您的break
屬於IF
范圍->如果年份不是1,則繼續第3種情況。
您可以使用if else
子句:
case 2:
if(year == 1) {
days = 29;
} else {
days = 28;
}
break;
但是我要提醒您, year != 1
並不意味着它的Feb獲得28天,也許您想要這樣:
case 2:
if(!isLeapYear(year)) {
days = 29;
} else {
days = 28;
}
break;
除了有關if
語句和switch
問題之外,首先使用leap年檢查的方法還需要解決一些問題。 這是下面原始代碼的開頭:
public static boolean isLeapYear(int year) {
if(year < 1 && year > 9999) {
return false;
} else {
...
條件year < 1 && year > 9999
永遠不會發生,因為year
不能同時小於1和大於9999,所以它是多余的。
除此之外,用於確定年份是否為a年的算法如下(以純英語顯示):
將以上所有考慮因素放入代碼中,可以使其更具可讀性:
public static boolean isLeapYear(int year) {
if (year % 4 != 0) {
// year is not evenly divisible by 4 (it has a remainder, can't be a leap year).
return false;
}
// year is evenly divisible by 4
if (year % 100 != 0) {
// divisible by 4 and not 100, it's a leap year
return true;
}
// divisible by 4 and also 100
if (year % 400 != 0) {
// divisible by 4, 100 and not by 400
return false;
}
// divisible by 4, 100 and 400
return true;
}
考慮到您的getDaysInMonth
方法,我們有以下幾種情況,其中1 =一月,2 =二月,依此類推:
30天:9月(9),4月(4),6月(6),11月(11)
31天:除2月(2)以外的所有其他日子(a年28、29)
public static int getDaysInMonth(int month, int year) {
switch (month) {
case 9:
case 4:
case 6:
case 11:
return 30;
case 2:
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
default:
return 31;
}
}
關於參數的驗證,如果您要接收用戶輸入,則應在用於計算的方法之外對所有參數進行驗證(傳遞已經驗證的方法輸入,而不是直接在其中進行驗證)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.