Java学习笔记_180711_常用类

1.Object类

Object类是java语言中所有类的根,所有的类都继承了Object类,拥有Object类的属性和方法。

1.1 clone()

返回对象的拷贝(克隆),对于基本类型会进行数值拷贝,对于引用类型只拷贝他的引用reference,也成为浅拷贝

1.2 equals(Object o)

判断当前对象与两外一个对象是否相等。未重写情况下不比较对象内容,只比较引用reference,未重写情况下与运算符“==”

 

 

 

 

*Math类

Math.round()整数四舍五入

负数5舍5.1入

 

 

*Calendar类

打印日历表

每周7天,一个月最多跨度6个星期,所以讲每个月天数放入int[6][7]的数组

行用Calendar.WEEK_OF_MONTH表示

列用Calendar.DAY_OF_WEEK表示

需要注意的是月份是从0开始的,Calendar.JANUARY=0;

星期的第一天是周日Calendar.SUNDAY=1,没有第0天

import java.util.Calendar;
import java.util.Scanner;


public class CalendarPrint {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int year = 1800;
		int month = 2;
		int day = 5;
		Scanner sc=new Scanner(System.in);
		
		System.out.print("输入年份: ");
		year=sc.nextInt();
		
		
		while(true){
			System.out.print("输入月份:");
			month=sc.nextInt();
			if(month<=12&&month>=1){
				break;
			}
			
			System.out.println("请输入1-12的整数!");
		}
		int maxdate = dayOfMonth(year,month);
		
		while(true){
			System.out.print("请输入日期:");
			day=sc.nextInt();
			if (day>=1&&day<=maxdate) {
				break;
			}
			System.out.println("超范围,请输入1-"+maxdate+"的数字!");
		}
		
		sc.close();
		
		Calendar cal=Calendar.getInstance();
		
		System.out.println();
		System.out.println("*************************************************************");
		//打印星期数
		String str=String.format("%1$-10s%2$-11s%3$-10s%4$-11s%5$-10s%6$-11s%7$-10s", "星期天","星期一","星期二","星期三","星期四","星期五","星期六");
		System.out.println(str);
		//创建日历数组
		int[][] dates= new int[6][7];
		
		//填充数组
		for(int i=1;i<=maxdate;i++){
			cal.set(year, month-1, i);
			int weekOfMonth=cal.get(Calendar.WEEK_OF_MONTH);
			int dayOfWeek=cal.get(Calendar.DAY_OF_WEEK);
			dates[weekOfMonth-1][dayOfWeek-1]=i;
		}
		//打印数组
		for(int i=0;i<dates.length;i++){
			for(int j=0;j<dates[i].length;j++){
				if(dates[i][j]!=0){
					if(dates[i][j]!=day)
						str=String.format("%1$-9d", dates[i][j]);
					else
						str=String.format("%1$-9s", dates[i][j]+"*");				
					
				}else {
					str=String.format("%1$-9s", "");
				}
				
				System.out.print(str);				
			}
			System.out.println();
		}
		System.out.println("*************************************************************");

	}
	
	static int dayOfMonth(int year,int month){
		int day=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((year%400==0)||((year%4==0)&&(year%100!=0)))
					day=29;
				else
					day=28;
				break;
			default:
				day = 0;
				break;
		}	
		
		return day;
	}
}

 

posted @ 2018-07-11 09:46  annofyf  阅读(169)  评论(0编辑  收藏  举报