Kiểm tra 1 tháng có bao nhiêu ngày

Yêu cầu
– Nhập vào tháng, năm
– Kiểm tra 1 tháng có bao nhiêu ngày

Giải thuật
– Dùng vòng lặp do while() để kiểm tra tính hợp hệ của tháng và năm nhập vào.
– Số ngày trong tháng 2 của năm nhuận khác với năm thường. Do đó, cần viết phương thức kiểm tra năm nhuận.

Code

package net.vncoding;
import java.util.Scanner;

public class JavaCore {
	
    static int  month_table[]      = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    static int  leap_month_table[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

    public static void main(String[] args) {
        
    	int month, year;
    	int day;
        Scanner sc = new Scanner(System.in);
        do {
        	System.out.print("month = ");
            month = sc.nextInt();
        }while(month > 12 || month < 1);
        
        do {
            System.out.print("year = ");
            year = sc.nextInt();
        }while(year < 1000 || year > 10000);
        
        
        day = day_of_month(month, year);
        System.out.println("The number of " + month + "/" + year + " is: " + day);
        
        sc.close();
    }
    
    public static boolean is_leap_year(int year) {
    	if((year%400 == 0) || (year%4 == 0 && year%100 != 0)) {
    	    return true;
    	}
    	else {
    	    return false;
    	}
    }
    
    public static int day_of_month(int month, int year) {
    	if(is_leap_year(year)) {
    	    return leap_month_table[month-1];
    	}
    	else {
    	    return month_table[month-1];
    	}
    }
}

Kết quả

Java - Số ngày trong tháng
Java – Số ngày trong tháng

Be the first to comment

Leave a Reply