天天看點

編寫 Java 程式,輸入年份和月份,使用 switch 結構計算對應月份的天數。 月份為 1、3、5、7、8、10、12 時,天數為 31 天。 月份為 4、6、9、11 時,天數為 30 天。 月一、使用 switch 語句實作代碼二、将代碼改寫回 if else 的選擇結構

有題如下:

編寫 Java 程式,輸入年份和月份,使用 switch 結構計算對應月份的天數。

月份為 1、3、5、7、8、10、12 時,天數為 31 天。

月份為 4、6、9、11 時,天數為 30 天。

月份為 2 時,若為閏年,天數為 29 天,否則,天數為 28 天。

實作如下程式:

編寫 Java 程式,輸入年份和月份,使用 switch 結構計算對應月份的天數。 月份為 1、3、5、7、8、10、12 時,天數為 31 天。 月份為 4、6、9、11 時,天數為 30 天。 月一、使用 switch 語句實作代碼二、将代碼改寫回 if else 的選擇結構

一、使用 switch 語句實作代碼

package rjxy2019_java_demo;

import java.util.Scanner;

public class SwitchWithDays {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Please enter a year:");
		int year = input.nextInt();
		System.out.println("Please enter a month:");
		int month = input.nextInt();
		int day = 0;
		boolean isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
		switch(month) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:day = 31;break;
		case 4:
		case 6:
		case 9:
		case 11:day = 30;break;
		case 2:if(isLeapYear == true) day = 29;
		else day = 28;break;
		default:System.out.println("Error:invalid input");
		System.exit(1);
		}
		System.out.println(year + "年" + month + "月一共" + day + "天");
	}
}
           

驗證,當輸入為 2009 年 2 月時:

編寫 Java 程式,輸入年份和月份,使用 switch 結構計算對應月份的天數。 月份為 1、3、5、7、8、10、12 時,天數為 31 天。 月份為 4、6、9、11 時,天數為 30 天。 月一、使用 switch 語句實作代碼二、将代碼改寫回 if else 的選擇結構

說明:

System.exit(status)

是在

System

類中定義的,調用這個方法可以終止程式。參數

status

為 0 表示程式正常結束。一個非 0 的狀态代碼表示非正常結束。

例如,我們輸入月份為 13 時,程式終止并輸出報錯資訊,如下圖所示:

編寫 Java 程式,輸入年份和月份,使用 switch 結構計算對應月份的天數。 月份為 1、3、5、7、8、10、12 時,天數為 31 天。 月份為 4、6、9、11 時,天數為 30 天。 月一、使用 switch 語句實作代碼二、将代碼改寫回 if else 的選擇結構

二、将代碼改寫回 if else 的選擇結構

package rjxy2019_java_demo;

import java.util.Scanner;

public class IfElseWithDays {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.println("Please enter a year:");
		int year = input.nextInt();
		System.out.println("Please enter a month:");
		int month = input.nextInt();
		int day = 0;
		boolean isLeapYear = ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
		if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month ==12) day = 31;
		else{
			if(month == 4 || month == 6 || month == 9 || month == 11) day = 30;
			else {
				if(month == 2) {
					if(isLeapYear == true) day = 29;
					else day = 28;
				}
				else {
					System.out.println("Error:invalid input");
					System.exit(1);
				}
			}
		}
		System.out.println(year + "年" + month + "月一共" + day + "天");
	}
}
           

輸出結果無誤,如下圖所示:

編寫 Java 程式,輸入年份和月份,使用 switch 結構計算對應月份的天數。 月份為 1、3、5、7、8、10、12 時,天數為 31 天。 月份為 4、6、9、11 時,天數為 30 天。 月一、使用 switch 語句實作代碼二、将代碼改寫回 if else 的選擇結構
編寫 Java 程式,輸入年份和月份,使用 switch 結構計算對應月份的天數。 月份為 1、3、5、7、8、10、12 時,天數為 31 天。 月份為 4、6、9、11 時,天數為 30 天。 月一、使用 switch 語句實作代碼二、将代碼改寫回 if else 的選擇結構
我是白鹿,一個不懈奮鬥的程式猿。望本文能對你有所裨益,歡迎大家的一鍵三連!若有其他問題、建議或者補充可以留言在文章下方,感謝大家的支援!