Java教程

第一次代码行数破百——打印1966年以后的月份的程序

本文主要是介绍第一次代码行数破百——打印1966年以后的月份的程序,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.util.Scanner;

public class Welcome
{
	public static void main(String[] args)
	{
		Scanner input = new Scanner(System.in);
		System.out.print("Enter your inquire year: ");
		int year = input.nextInt();
		int month;
		do
		{
		System.out.print("Enter your inquire month between 1 and 12: ");
		month = input.nextInt();
		}while(month < 1 || month > 12);
		printTop(month,year);
		printBody(month,year);
	}
	public static void printTop(int mon, int year)
	{
		System.out.println("      "+getMonthName(mon)+" "+year);
		System.out.println("---------------------------");
		System.out.println(" Sun Mon Tue Wed Thu Fri Sat");
	}
	public static String getMonthName(int mon)
	{
		String message=" ";
		switch(mon)
		{
		case 1: message = "January";break;
		case 2: message = "February";break;
		case 3: message = "March";break;
		case 4: message = "April";break;
		case 5: message = "May";break;
		case 6: message = "June";break;
		case 7: message = "July";break;
		case 8: message = "August";break;
		case 9: message = "September";break;
		case 10: message = "October";break;
		case 11: message = "November";break;
		case 12: message = "December";break;
		}
		return message;
	}
	public static int startDay(int mon,int year)
	{
		int runYear = 0,norunYear = 0;
		for(int i = 1966;i <= year;i++)
		{
			if(i % 400 == 0 || (i % 4 == 0 && i % 100 != 0))
			{
				runYear++;
			}
			else
			{
				norunYear++;
			}
		}
		int totalMonDay = 0;
		for(int i = 1; i <= mon; i++)
		{
			totalMonDay += dayOfMonth(mon,year);
		}
		return (((runYear * 366+norunYear * 365) + 6) +totalMonDay) % 7;
	}
	public static void printBody(int mon,int year)
	{
		for(int i = 1;i <= startDay(mon,year);i++)
		{
			System.out.print("    ");
		}
		for(int i = 1;i <= dayOfMonth(mon,year);i++)
		{
			System.out.printf("%4d",i);
			if((i + startDay(mon,year)) % 7 == 0)
			{
				System.out.println();
			}
		}
	}
	public static int dayOfMonth(int month,int i)
	{
		if(i % 400 == 0 || (i % 4 == 0 && i % 100 != 0))
		{
			if(month == 1 || month == 3 || month == 5 || month == 7 || month ==8 || month ==10 || month == 12)
				return 31;
			else if(month ==2)
				return 29;
			else
				return 30;
		}
		else
		{
			if(month == 1 || month == 3 || month == 5 || month == 7 || month ==8 || month ==10 || month == 12)
				return 31;
			else if(month ==2)
				return 28;
			else
				return 30;
		}
	}
}

  

第一次自己敲出破百行的代码!

唯一美中不足的是打印的月份不连续,所以结果是错的。偶尔碰巧能符合现实。比如现在的月份。不过真的挺有进步!

前路漫漫,勇往直前!(等着破300行了我再记录!)

这篇关于第一次代码行数破百——打印1966年以后的月份的程序的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!