Home > Java > Javagetting Started > body text

Use java to create a perpetual calendar

王林
Release: 2020-11-09 15:15:07
forward
3520 people have browsed it

Use java to create a perpetual calendar

This article shares the method of making a perpetual calendar. If there is anything incorrect in the article, you are welcome to criticize and correct it.

(Recommended tutorial: java course)

Code implementation:

package com.softeem.test01;
import java.time.Month;
import java.time.Year;
import java.util.Scanner;
public class DynamicCalendar {
	private int y;
	private int m;
	public DynamicCalendar(int y, int m) {
		this.y = y;
		this.m = m;
	}
	public boolean year(int ye) {
		return ye % 4 == 0 && ye % 100 != 0 || ye % 400 == 0;
	}
	public int month(int ye, int mon) {
		if (mon < 1 || mon > 12) {
			System.out.println("输入错误");
			return 0;
		}
		switch (mon) {
		case 4:
		case 6:
		case 9:
		case 11:
			return 30;
		case 2:
			return year(ye) ? 29 : 28;
		default:
			return 31;
		}
	}
	public int method() {
		int count = 0;
		for (int i = 1900; i < this.y; i++) {
			count += year(i) ? 366 : 365;
		}
 		for (int i = 1; i < m; i++) {
			count += month(this.y, i);
		}
		return count;
	}

	public void printCalendar() {
		int space = method() % 7;
		int count = month(y, m);
		System.out.println("==============万年历【" + y + "】年【" + m + "】月===================");
		System.out.println("一\t二\t三\t四\t五\t六\t日");
		System.out.println("==================================================");
		int sum = 0;
		for (int i = 0; i < space; i++) {
			System.out.print("\t");
			sum++;
		}
		for (int i = 1; i < count; i++) {
			sum++;
			System.out.print(i + "\t");
			if (sum == 7) {
				System.out.println();
				sum = 0;
			}
		}
	}
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.print("请输入年份:");
		int y = sc.nextInt();
		System.out.print("请输入月份:");
		int m = sc.nextInt();
		DynamicCalendar dc = new DynamicCalendar(y, m);
		dc.printCalendar();
	}
}
Copy after login

Output result:

Use java to create a perpetual calendar

Related recommendations:Getting started with java

The above is the detailed content of Use java to create a perpetual calendar. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template