JAVA范例 十一)JAVA常用类

  11.1 数学Math类

  实例186 求圆周率∏值

package Chapter11.math;

public class CirclePI {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int n = 100000;// 投的点数
		int m = 0;// 投中的个数
		double x, y;// x和y坐标点
		for (int i = 0; i < n; i++) {
			// 随机产生一个点
			x = Math.random();
			y = Math.random();
			// 计算这个点是位于圆内还是圆外
			if (x * x + y * y <= 1)// 判断掷入的这个点是不是在圆内
				m++;
		}
		// 统计得到π的值
		System.out.println("根据随机数计算π的结果如下:");
		System.out.println("\tpi =" + (double) m / n * 4);
	}
}

 

  实例187 求对数值

package Chapter11.math;

public class Logarithm {

	/**
	 * @param 求对数
	 */
	public static void main(String[] args) {
		double m = 8;// 声明一个double变量。
		double value = Math.log(m);// 返回(底数是 e)double 值的自然对数。
		double value1 = Math.log10(m);// 返回double值的底数为10的对数。
		double value2 = Math.log1p(m);// 返回参数与 1 的和的自然对数。
		System.out.println("m的自然对数为:" + value);
		System.out.println("以10为底m的对数为:" + value1);
		System.out.println("(m+1)的自然对数为:" + value2);
	}
}

 

  实例188 使用取整函数

package Chapter11.math;

import java.util.Scanner;

public class Intpart {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		double num;
		Scanner in = new Scanner(System.in);// 由键盘输入一个浮点数
		System.out.print("请输入一个浮点数:");
		num = in.nextDouble();// 获取这个浮点数
		int rint = (int) Math.rint(num);// 调用Math类的rint方法
		System.out.println(num + "四舍五入得到整数:" + rint);
		long round = Math.round(num);// 调用Math类的round方法
		System.out.println(num + "四舍五入得到长整数:" + round);
		int max = (int) Math.floor(num);// 调用Math类的floor方法
		System.out.println("小于" + num + "的最大正整数:" + max);
		int min = (int) Math.ceil(num);// 调用Math类的ceil方法
		System.out.println("大于" + num + "的最小正整数:" + min);
	}
}

 

  11.2 Random类的使用

  实例189 随机数 

package Chapter11.Random;

import java.util.Random;

public class RandomClass {

	public static void randomTypes() {// 获取各种数据类型的随机数
		System.out.println("1. 使用Random类的构造方法生成随机数的示例如下:");
		Random rdm = new Random();// 使用默认的构造方法创建一个Random对象
		int a = 0, b = 0, c = 0, d = 0, e = 0;// 定义计算变量
		while (true) {// 随机产生5个各种类型的随机数
			if (a < 5) {
				if (a == 0) {
					System.out.println("生成double型的随机数列如下:");
				}
				System.out.print(rdm.nextDouble() + " "); // 按均匀分布产生[0,
				// 1)范围的double
				a++;
			} else if (a == 5 && b < 5) {
				if (a == 5 && b == 0) {
					System.out.println("\n生成float型的随机数列如下:");
				}
				System.out.print(rdm.nextFloat() + " "); // 按均匀分布产生大于等于0,小于1的float
				b++;
			} else if (b == 5 && c < 5) {
				if (b == 5 && c == 0) {
					System.out.println("\n生成long型的随机数列如下:");
				}
				System.out.print(rdm.nextLong() + " "); // 按均匀分布产生长整数
				c++;
			} else if (c == 5 && d < 5) {
				if (c == 5 && d == 0) {
					System.out.println("\n生成int型的随机数列如下:");
				}
				System.out.print(rdm.nextInt() + " "); // 按均匀分布产生整数
				d++;
			} else if (d == 5 && e < 5) {
				if (d == 5 && e == 0) {
					System.out.println("\n生成按正态分布产生的double型随机数列如下:");
				}
				System.out.print(rdm.nextGaussian() + " "); // 按正态分布产生随机数
				e++;
			} else if (e == 5) {
				break;
			}
		}
	}

	public static void nextInt() { // 获取指定范围内的随机数
		System.out.println("\n\n2. 在指定范围内产生随机序列:");
		System.out.print("在[0,8)的范围内产生的随机整数序列如下: ");
		Random rdm = new Random();
		for (int i = 0; i < 5; i++) {
			System.out.print(rdm.nextInt(7) + "  "); // Random的nextInt(int,n)方法返回一个[0,
			// n]范围内的随机数
		}
		System.out.println();
		System.out.print("在[5,50)的范围内产生的随机整数序列如下:");
		for (int i = 0; i < 5; i++) {
			System.out.print(5 + rdm.nextInt(45) + "  ");
		}
		System.out.println();
		System.out.print("在[0,100)范围内生成float型的随机整数序列如下: ");
		for (int i = 0; i < 5; i++) {
			System.out.print((int) (rdm.nextFloat() * 100) + "  ");
		}
		System.out.println("\n");
	}

	public static void RandomSeed() { // 使用种子来创建随机数列
		// 构造函数的参数是long类型,是生成随机数的种子。
		System.out.println("3. 使用种子产生随机数");
		Random rad = new Random(12);// 创建第一个Random对象
		// 通过种子相同的两个Random对象来验证"种子相同,生成的随机数序列也是相同的"。
		System.out.println("使用种子为12的Random对象生成[10,100)内随机整数序列: ");
		for (int i = 0; i < 5; i++) {
			System.out.print(10 + rad.nextInt(90) + "  ");
		}
		System.out.println();
		Random rad1 = new Random(12);// 创建另一个Random对象
		System.out.println("使用另一个种子为12的Random对象生成[10,100)内随机整数序列: ");
		for (int i = 0; i < 5; i++) {
			System.out.print(10 + rad1.nextInt(90) + "  ");
		}
		System.out.println("\n");
	}

	public static void main(String[] args) {// 调用各方法
		randomTypes();
		nextInt();
		RandomSeed();
	}
}

 

  实例190 验证码

package Chapter11.Random;

import java.util.Random;

public class Code {

	
	static Random rd = new Random();

	public static void main(String[] args) {
		numCode();
		charCode();
		chineseCode();
		mixCode();
	}

	public static void numCode() {// 由0-9组成的全数字验证码
		System.out.print("获取的5位数字验证码:");
		for (int i = 0; i < 5; i++) {
			int n = rd.nextInt(10);
			System.out.print(n + " ");

		}
		System.out.println();
	}

	public static void charCode() {// 英文字母和标点符号组成的字符验证码
		System.out.print("\n获取的5位字符验证码:");
		for (int i = 0; i < 5; i++) {
			int n = 65 + rd.nextInt(58);
			System.out.print((char) n + " ");

		}
		System.out.println();
	}

	public static void chineseCode() {// 全部由中文组成的验证码
		System.out.print("\n获取的5位汉字验证码:");
		for (int i = 0; i < 5; i++) {
			int n = 20000 + rd.nextInt(10000);
			System.out.print((char) n + " ");
		}
		System.out.println();
	}

	public static void mixCode() {// 字符+数字的混合验证码
		System.out.print("\n获取的5位混合验证码:");
		for (int i = 0; i < 5; i++) {
			int n = rd.nextInt(123);
			if (n < 65) {
				System.out.print(n % 10 + " ");
			} else {
				System.out.print((char) n + " ");
			}
		}
	}
}

 

  11.3 Date类和Calendar类

  实例191 使用Date类获取系统的当前时间

package Chapter11.date;

import java.util.Date;

public class GetTimer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Date date = new Date();// 创建一个Date对象
		System.out.println("距1970年1月1日00:00:00时间已经过了" + date.getTime() + "毫秒");// 调用Date类的getTime方法
		System.out.println("当前的时间:" + date.toGMTString());// 调用Date类的toGMTString方法,不过此方法已过时

	}

}

 

  实例192 使用DateFormat类获取系统的当前时间

package Chapter11.date;

import java.text.DateFormat;
import java.util.Date;

public class DateFormatClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DateFormatClass.date_Format();
	}
	public static void date_Format() {
		System.out.println("使用DateFormat类获取系统的当前时间的示例如下所示:");
		Date date = new Date();
		DateFormat shortDateFormat = DateFormat.getDateTimeInstance(
				DateFormat.SHORT, DateFormat.SHORT);
		DateFormat mediumDateFormat = DateFormat.getDateTimeInstance(
				DateFormat.MEDIUM, DateFormat.MEDIUM);
		DateFormat longDateFormat = DateFormat.getDateTimeInstance(
				DateFormat.LONG, DateFormat.LONG);
		DateFormat fullDateFormat = DateFormat.getDateTimeInstance(
				DateFormat.FULL, DateFormat.FULL);
		System.out.println("SHORT 模式的日期为:" + shortDateFormat.format(date));
		System.out.println("MEDIUM 模式的日期为:" + mediumDateFormat.format(date));
		System.out.println("LONG 模式的日期为:" + longDateFormat.format(date));
		System.out.println("FULL 模式的日期为:" + fullDateFormat.format(date));
	}

}

 

  实例193 使用GregorianCalendar类获取系统的当前时间

package Chapter11.date;

import java.text.DateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

public class GregorianCalendarClass {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		GregorianCalendarClass calendarClass = new GregorianCalendarClass();
		calendarClass.Date_Format();

	}
	public static void Date_Format() {
		System.out.println("使用GregorianCalendar类获取系统的当前时间的示例如下所示");
		DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
														// 创建一个GregorianCalendar日历对象
		GregorianCalendar cal = new GregorianCalendar();
														// 将日历系统的日期和时间设置给cal
		cal.setTime(new Date());
		System.out.println("GregorianCalendar类的日期: "
				+ dateFormat.format(cal.getTime()));
														// 将DAY_OF_WEEK的值设为MONDAY
		cal.set(GregorianCalendar.DAY_OF_WEEK, GregorianCalendar.SUNDAY);
		System.out.println("在本周内,星期日的日期为: " + dateFormat.format(cal.getTime()));
		int count = 0;
		System.out.println("符合条件的日期如下:");
		while (count <= 5) {
														// DAY_OF_MONTH的值设为7
			cal.add(GregorianCalendar.DAY_OF_MONTH, 7);
														// 判断某月的某日的日期是15号且是星期日
			if (cal.get(GregorianCalendar.DAY_OF_MONTH) == 15) {
				count++;
				System.out.println(dateFormat.format(cal.getTime()));
			}
		}
	}

}

 

  实例194 使用SimpleDateFormat类获取系统的当前时间

package Chapter11.date;

import java.text.SimpleDateFormat;
import java.util.*;

public class SimpleDateClass {
	public static void main(String[] args) {
		SimpleDateClass.Simple_Format();// 调用Simple_Date方法
	}

	public static void Simple_Format() {
		System.out.println("SimpleDateFormat类获取系统当前的时间如下:");
		// 创建一个日期格式化,日期的形式为EEEE-MMMM-dd-yyyy
		SimpleDateFormat bartDateFormat = new SimpleDateFormat(
				"EEEE-MMMM-dd-yyyy");
		// 创建一个日期格式化,日期的形式为yyyy.MM.dd G 'at' HH:mm:ss z
		SimpleDateFormat b = new SimpleDateFormat(
				"yyyy.MM.dd G 'at' HH:mm:ss z");
		// 创建一个日期格式化,日期的形式为EEE, MMM d, ''yy
		SimpleDateFormat b1 = new SimpleDateFormat("EEE, MMM d, ''yy");
		// 创建一个日期格式化,日期的形式为h:mm a
		SimpleDateFormat b2 = new SimpleDateFormat("h:mm a");
		// 创建一个日期格式化,日期的形式为EEE, d MMM yyyy HH:mm:ss Z
		SimpleDateFormat b3 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
		// 创建一个日期格式化,日期的形式为yyMMddHHmmssZ
		SimpleDateFormat b4 = new SimpleDateFormat("yyMMddHHmmssZ");
		Date date = new Date();
		System.out.println("第一种表式形式:" + bartDateFormat.format(date));
		System.out.println("第二种表式形式:" + b.format(date));
		System.out.println("第三种表式形式:" + b1.format(date));
		System.out.println("第四种表式形式:" + b2.format(date));
		System.out.println("第五种表式形式:" + b3.format(date));
		System.out.println("第六种表式形式:" + b4.format(date));
	}

}

 

  实例195 显示某年某月某一周的信息

package Chapter11.date;

import java.util.Calendar;

public class ShowWeek {
	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();// 获取一个Calendar对象
		int count = 0;// 定义一个计数变量
		calendar.set(Calendar.YEAR, 2010);// 设置年份
		calendar.set(Calendar.MONTH, 2);// 设置月份
		calendar.set(Calendar.DATE, 8);// 设置日期
		System.out.println("2010年3月9号一周内的日历如下:");
		System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
		while (count < 7) {
			calendar.add(Calendar.DAY_OF_MONTH, 1);// 设置添加日历的周期为1
			int day = calendar.getTime().getDay();// 获取日历的星期几表示数,例如:0:表示星期日
			if (count == 0) {// 根据星期几来决定输入几个tab
				for (int i = 0; i < day; i++) {
					System.out.print("\t");
				}
			}
			if (day == 0) {// 如果是周日了则换行
				System.out.println();
			}
			System.out.print(calendar.getTime().getDate() + "\t");// 获取日历中日期数
			count++;
		}
	}
}

 

  实例196 显示某年某月的信息

package Chapter11.date;

import java.util.Calendar;

public class ShowMonth {
	public static void main(String[] args) {
		Calendar calendar = Calendar.getInstance();// 获取一个Calendar对象
		int count = 0;// 定义一个计数变量
		int year = 2011;
		int month = 5;
		calendar.set(Calendar.YEAR, year);// 设置年份
		calendar.set(Calendar.MONTH, month);// 设置月份
		calendar.set(Calendar.DATE, 0);// 设置日期
		int days = chooseMonth(month + 1);
		System.out.println(year + " 年 " + (month + 1) + " 月 的 日 历 如 下:");
		System.out.println("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六");
		while (count < days) {
			calendar.add(Calendar.DAY_OF_MONTH, 1);// 设置添加日历的周期为1
			int day = calendar.getTime().getDay();// 获取日历的星期几表示数,例如:0:表示星期日
			if (count == 0) {// 根据星期几来决定输入几个tab
				for (int i = 0; i < day; i++) {
					System.out.print("\t");
				}
			}
			if (day == 0) {// 如果是周日了则换行
				System.out.println();
			}
			System.out.print(calendar.getTime().getDate() + "\t");// 获取日历中日期数
			count++;
		}
	}
	public static int chooseMonth(int m) {// 根据月份选择天数
		int days = 0;
		switch (m) {
		case 2:
			days = 28;
			break;
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			days = 31;
			break;
		case 4:
		case 6:
		case 9:
		case 11:
			days = 30;
			break;
		default:
			days = 0;
		}
		return days;
	}
}

 

  实例197 时间的设置与获取

package Chapter11.date;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;

public class WriteTime extends JFrame {
	private JPanel panel;

	private BorderLayout borderLayout1 = new BorderLayout();

	// 创建组件实例
	private JLabel jLabel1 = new JLabel();

	private JButton jButton1 = new JButton();

	private JPanel jPanel1 = new JPanel();

	private JTextField jtf1 = new JTextField();

	private JTextField jtf2 = new JTextField();

	private JTextField jtf3 = new JTextField();

	private JTextField jtf4 = new JTextField();

	private JTextField jtf5 = new JTextField();

	private JTextField jtf6 = new JTextField();

	private TitledBorder tb1;

	private TitledBorder tb2;

	private TitledBorder tb3;

	private TitledBorder tb4;

	private TitledBorder tb5;

	private TitledBorder tb6;

	private TitledBorder tb7;

	private GridLayout gridLayout = new GridLayout();

	String year, month, day, hour, minute, second;// 各时间项

	Calendar cal = Calendar.getInstance();// 创建Calendar的实例

	private void Jinit() {
		// 初始化时间项的值
		this.year = String.valueOf(cal.get(Calendar.YEAR));//
		this.month = String.valueOf(cal.get(Calendar.MONTH));
		this.day = String.valueOf(cal.get(Calendar.DATE));
		this.hour = String.valueOf(cal.get(Calendar.HOUR));
		this.minute = String.valueOf(cal.get(Calendar.MINUTE));
		this.second = String.valueOf(cal.get(Calendar.SECOND));
		// 创建TitledBorder边界实例
		panel = (JPanel) this.getContentPane();
		tb1 = new TitledBorder(BorderFactory.createEtchedBorder(Color.red,
				Color.white), "年份");
		tb2 = new TitledBorder(BorderFactory.createEtchedBorder(Color.red,
				Color.white), "月份");
		tb3 = new TitledBorder(BorderFactory.createEtchedBorder(Color.red,
				Color.white), "日期");
		tb4 = new TitledBorder(BorderFactory.createEtchedBorder(Color.red,
				Color.white), "时");
		tb5 = new TitledBorder(BorderFactory.createEtchedBorder(Color.red,
				Color.white), "分");
		tb6 = new TitledBorder(BorderFactory.createEtchedBorder(Color.red,
				Color.white), "秒");
		tb7 = new TitledBorder(BorderFactory.createEtchedBorder(Color.red,
				Color.white), "设置时间");
		jLabel1.setFont(new Font("Dialog", Font.BOLD, 14));
		jLabel1
				.setText("Now:" + this.year + "年" + this.month + "月" + this.day
						+ "日" + this.hour + "时" + this.minute + "分"
						+ this.second + "秒");// 显示时间
		panel.setLayout(borderLayout1);
		this.setSize(new Dimension(468, 140));
		this.setVisible(true);
		this.setTitle("时间的设置与获取示例");
		jButton1.setText("重新获取时间");

		jButton1.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				jButton1_actionPerformed(e);

			}

		});

		// 设置JTextField组件的初始显示数,并添加边界
		jtf1.setBorder(this.tb1);
		jtf1.setText(this.year);
		jtf2.setBorder(this.tb2);
		jtf2.setText(this.month);
		jtf3.setBorder(this.tb3);
		jtf3.setText(this.day);
		jtf4.setBorder(this.tb4);
		jtf4.setText(this.hour);
		jtf5.setBorder(this.tb5);
		jtf5.setText(this.minute);
		jtf6.setBorder(this.tb6);
		jtf6.setText(this.second);
		jPanel1.setLayout(gridLayout);
		jPanel1.setBorder(this.tb7);
		// 添加各组件
		panel.add(jLabel1, BorderLayout.SOUTH);
		panel.add(jButton1, BorderLayout.CENTER);
		panel.add(jPanel1, BorderLayout.NORTH);
		jPanel1.add(jtf1, null);
		jPanel1.add(jtf2, null);
		jPanel1.add(jtf3, null);
		jPanel1.add(jtf4, null);
		jPanel1.add(jtf5, null);
		jPanel1.add(jtf6, null);
	}

	public void jButton1_actionPerformed(ActionEvent e) {
		// 设置时间
		cal.set(Integer.parseInt(this.jtf1.getText()), Integer
				.parseInt(this.jtf2.getText()), Integer.parseInt(this.jtf3
				.getText()), Integer.parseInt(this.jtf4.getText()), Integer
				.parseInt(this.jtf5.getText()), Integer.parseInt(this.jtf6
				.getText()));
		// 更新时间项数据
		this.year = String.valueOf(cal.get(Calendar.YEAR));
		this.month = String.valueOf(cal.get(Calendar.MONTH));
		this.day = String.valueOf(cal.get(Calendar.DATE));
		this.hour = String.valueOf(cal.get(Calendar.HOUR));
		this.minute = String.valueOf(cal.get(Calendar.MINUTE));
		this.second = String.valueOf(cal.get(Calendar.SECOND));
		// 显示当前时间
		jLabel1
				.setText("Now:" + this.year + "年" + this.month + "月" + this.day
						+ "日" + this.hour + "时" + this.minute + "分"
						+ this.second + "秒");

	}

	public static void main(String[] args) {
		new WriteTime().Jinit();
	}

}

 

  实例198 万年历(农历和阳历的互换)

package com.java;

import java.util.Calendar;

public class LunarCalendar {
	public static void main(String[] args) {
		Solar s = new Solar();
		s.getDate(2020, 9);
		String t = MutualConversion.solarToLundar(2009, 10, 12);
		String[] str = t.split("-");
		Lunar la = new Lunar(Integer.parseInt(str[0]), Integer
				.parseInt(str[1]), Integer.parseInt(str[2])); 
		System.out.println("\n\n阳历2009-10-12日对应的农历日期为:"+la.toString(1)+" "+la.toWeek());
		String t1 = MutualConversion.lundarToSolar(2019, 1, 1);
		String[] str1 = t1.split("-");
		Solar s1 = new Solar(Integer.parseInt(str1[0]), Integer
				.parseInt(str1[1]), Integer.parseInt(str1[2])); 
		System.out.println("\n农历2019-1-1日对应的阳历日期为:"+s1.toString()+" "+s1.toWeek());
	}
}
// 自定义日历类,其作用是实现阳历和农历日期相互转换的功能
class MutualConversion {
	// 阵列storeLunarMonth存储在每月一天的资料,每年从1901年到2100年的农历,农历只能是29或30天,
	// 每月表达12(或13)的二进制位在一年内,这是30 1中的相应位置的形式天,否则,29天
	private static final int[]storeLunarMonth = {
		0x4ae0,0xa570,0x5268,0xd260,0xd950,0x6aa8,
		0x56a0,0x9ad0,0x4ae8,0x4ae0,//1910
		0xa4d8,0xa4d0,0xd250,0xd548,0xb550,0x56a0,
		0x96d0,0x95b0,0x49b8,0x49b0,//1920
		0xa4b0,0xb258,0x6a50,0x6d40,0xada8,
		0x2b60,0x9570,0x4978,0x4970,0x64b0, //1930
		0xd4a0,0xea50,0x6d48,0x5ad0,0x2b60,
		0x9370,0x92e0,0xc968,0xc950,0xd4a0, //1940
		0xda50,0xb550,0x56a0,0xaad8,0x25d0,
		0x92d0,0xc958,0xa950,0xb4a8,0x6ca0, //1950
		0xb550,0x55a8,0x4da0,0xa5b0,0x52b8,
		0x52b0,0xa950,0xe950,0x6aa0,0xad50, //1960
		0xab50,0x4b60,0xa570,0xa570,
		0x5260,0xe930,0xd950,0x5aa8,0x56a0,0x96d0, //1970
		0x4ae8,0x4ad0,0xa4d0,0xd268,0xd250,
		0xd528,0xb540,0xb6a0,0x96d0,0x95b0, //1980
		0x49b0,0xa4b8,0xa4b0,0xb258,0x6a50,
		0x6d40,0xada0,0xab60,0x9370,0x4978, // 1990
		0x4970,0x64b0,0x6a50,0xea50,0x6b28,
		0x5ac0,0xab60,0x9368,0x92e0,0xc960, //2000
		0xd4a8,0xd4a0,0xda50,0x5aa8,0x56a0,
		0xaad8,0x25d0,0x92d0,0xc958,0xa950, //2010
		0xb4a0,0xb550,0xb550,0x55a8,0x4ba0
		,0xa5b0,0x52b8,0x52b0,0xa930,0x74a8, //2020
		0x6aa0,0xad50,0x4da8,0x4b60,0x9570,
		0xa4e0,0xd260,0xe930,0xd530,0x5aa0, //2030
		0x6b50,0x96d0,0x4ae8,0x4ad0,0xa4d0,
		0xd258,0xd250,0xd520,0xdaa0,0xb5a0, //2040
		0x56d0,0x4ad8,0x49b0,0xa4b8,0xa4b0,
		0xaa50,0xb528,0x6d20,0xada0,0x55b0 //2050
	};
	// 阵列storeLunarLeapMonth存储的是农历1901年至2050年闰月的信息,0表示该年没有闰月,每个字符元素表示的存储两年。
	// 例如0x50该字符存储的是2009和2010年,0x表示八进制,5表示2009年闰5月,0表示2010没有闰月
	private static final char[] storeLunarLeapMonth = { 0x00, 0x50, 0x04, 0x00,
			0x20, // 1910
			0x60, 0x05, 0x00, 0x20, 0x70, // 1920
			0x05, 0x00, 0x40, 0x02, 0x06, // 1930
			0x00, 0x50, 0x03, 0x07, 0x00, // 1940
			0x60, 0x04, 0x00, 0x20, 0x70, // 1950
			0x05, 0x00, 0x30, 0x80, 0x06, // 1960
			0x00, 0x40, 0x03, 0x07, 0x00, // 1970
			0x50, 0x04, 0x08, 0x00, 0x60, // 1980
			0x04, 0x0a, 0x00, 0x60, 0x05, // 1990
			0x00, 0x30, 0x80, 0x05, 0x00, // 2000
			0x40, 0x02, 0x07, 0x00, 0x50, // 2010
			0x04, 0x09, 0x00, 0x60, 0x04, // 2020
			0x00, 0x20, 0x60, 0x05, 0x00, // 2030
			0x30, 0xb0, 0x06, 0x00, 0x50, // 2040
			0x02, 0x07, 0x00, 0x50, 0x03 // 2050
	};
	// 用矩阵存领存储从1901~2050年每一年的阳历和农历的偏移天数
	private static final char[] offseOfDays = { 49, 38, 28, 46, 34, 24, 43, 32,
			21, 40, // 1910
			29, 48, 36, 25, 44, 34, 22, 41, 31, 50, // 1920
			38, 27, 46, 35, 23, 43, 32, 22, 40, 29, // 1930
			47, 36, 25, 44, 34, 23, 41, 30, 49, 38, // 1940
			26, 45, 35, 24, 43, 32, 21, 40, 28, 47, // 1950
			36, 26, 44, 33, 23, 42, 30, 48, 38, 27, // 1960
			45, 35, 24, 43, 32, 20, 39, 29, 47, 36, // 1970
			26, 45, 33, 22, 41, 30, 48, 37, 27, 46, // 1980
			35, 24, 43, 32, 50, 39, 28, 47, 36, 26, // 1990
			45, 34, 22, 40, 30, 49, 37, 27, 46, 35, // 2000
			23, 42, 31, 21, 39, 28, 48, 37, 25, 44, // 2010
			33, 23, 41, 31, 50, 39, 28, 47, 35, 24, // 2020
			42, 30, 21, 40, 28, 47, 36, 25, 43, 33, // 2030
			22, 41, 30, 49, 37, 26, 44, 33, 23, 42, // 2040
			31, 21, 40, 29, 47, 36, 25, 44, 32, 22, // 2050
	};
	static boolean isLeapYearOfSolar(int year) {// 判断是否有闰年
		return ((year % 4 == 0) && (year % 100 != 0) || year % 400 == 0);
	}
	// 获取阳历中每个月的天数
	static int getSolarMonthOfDays(int year, int month) {
		if ((month == 1) || (month == 3) || (month == 5) || (month == 7)
				|| (month == 8) || (month == 10) || (month == 12))
			return 31;
		else if ((month == 4) || (month == 6) || (month == 9) || (month == 11))
			return 30;
		else if (month == 2) {
			if (isLeapYearOfSolar(year))
				return 29;
			else
				return 28;
		} else
			return 0;
	}
	// 获取新年的偏移天
	static int L_getOffsetOfDays(int year, int month, int day) {
		int days = 0;
		for (int i = 1; i < month; i++) {
			days += getSolarMonthOfDays(year, i);
		}
		days += day - 1;
		return days;
	}
	static int L_getLeapMonth(int year) {
		char month = storeLunarLeapMonth[(year - 1901) / 2];
		if (year % 2 == 0)
			return (month & 0x0f);
		else
			return (month & 0xf0) >> 4;
	}
	// 获取当前年月的农历月
	static int L_getMonthDays(int year, int month) {
		int leapMonth = L_getLeapMonth(year);
		if ((month > 12) && (month - 12 != leapMonth) || (month < 0)) {
			System.out.println("输入的月份有错误");
			return -1;
		}
		if (month - 12 == leapMonth) {
			if ((storeLunarMonth[year - 1901] & (0x8000 >> leapMonth)) == 0)
				return 29;
			else
				return 30;
		}
		if ((leapMonth > 0) && (month > leapMonth))
			month++;
		if ((storeLunarMonth[year - 1901] & (0x8000 >> (month - 1))) == 0)
			return 29;
		else
			return 30;
	}
	// 获取当前年份的农历年
	static int getLunarYear(int year) {
		int iYearDays = 0;
		int leapMonth = L_getLeapMonth(year);
		for (int i = 1; i < 13; i++)
			iYearDays += L_getMonthDays(year, i);
		if (leapMonth > 0)
			iYearDays += L_getMonthDays(year, leapMonth + 12);
		return iYearDays;
	}
	static int getOffsetOfDays(int year, int month, int day) {
		int days = 0;
		int leapMonth = L_getLeapMonth(year);
		if ((leapMonth > 0) && (leapMonth == month - 12)) {
			month = leapMonth;
			days += L_getMonthDays(year, month);
		}
		for (int i = 1; i < month; i++) {
			days += L_getMonthDays(year, i);
			if (i == leapMonth)
				days += L_getMonthDays(year, leapMonth + 12);
		}
		days += day - 1;
		return days;
	}
	// 阳历转换成农历
	static String solarToLundar(int year, int month, int day) {
		int L_day, L_month, L_year;
		int days = L_getOffsetOfDays(year, month, day);
		int leapMonth = L_getLeapMonth(year);
		if (days < offseOfDays[year - 1901]) {
			L_year = year - 1;
			days = offseOfDays[year - 1901] - days;
			L_day = days;
			for (L_month = 12; days > L_getMonthDays(L_year, L_month); L_month--) {
				L_day = days;
				days -= L_getMonthDays(L_year, L_month);
			}
			if (0 == L_day)
				L_day = 1;
			else
				L_day = L_getMonthDays(L_year, L_month) - days + 1;
		} else {
			L_year = year;
			days -= offseOfDays[year - 1901];
			L_day = days + 1;
			for (L_month = 1; days >= 0; L_month++) {
				L_day = days + 1;
				days -= L_getMonthDays(L_year, L_month);
				if ((leapMonth == L_month) && (days > 0)) {
					L_day = days;
					days -= L_getMonthDays(L_year, L_month + 12);
					if (days <= 0) {
						L_month += 12 + 1;
						break;
					}
				}
			}
			L_month--;
		}
		return "" + L_year + "-" + L_month + "-" + L_day;
	}
	// 农历转换成阳历
	static String lundarToSolar(int year, int month, int day) {
		int S_year, S_month, S_day;
		int days = getOffsetOfDays(year, month, day) + offseOfDays[year - 1901];
		int iYearDays = isLeapYearOfSolar(year) ? 366 : 365;
		if (days >= iYearDays) {
			S_year = year + 1;
			days -= iYearDays;
		} else {
			S_year = year;
		}
		S_day = days + 1;
		for (S_month = 1; days >= 0; S_month++) {
			S_day = days + 1;
			days -= getSolarMonthOfDays(S_year, S_month);
		}
		S_month--;
		return "" + S_year + "-" + S_month + "-" + S_day;
	}
}
// 自定义星期类
class CustomWeek {
	int week;
	private String weeks[] = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };// 定义一个String数组,存储一周七天的星期
	public CustomWeek() {// 默认星期为星期日
		week = 0;
	}
	// 0:星期日 1:星期一 2:星期二 3:星期三 4:星期四 5:星期五 6:星期六
	public CustomWeek(int w) {
		if ((w > 6) || (w < 0)) {
			System.out
					.println("CustomWeek out of range, I think you want Sunday");
			this.week = 0;
		} else
			this.week = w;
	}
	public String toString() {
		return weeks[week];
	}
}
// 自定义日期类
class CustomDate {
	public int year;
	public int month;
	public int day;
	private static int checkYear(int year) {// 检察输入的年份是否在指定的年份范围中
		if ((year > 1901) && (year < 2050))
			return year;
		else {
			System.out.println("输入的年份不在1901~2050之间,默认年份为1991年");
			return 1991;
		}
	}
	// 构造方法
	public CustomDate(int year, int month, int day) {
		this.year = checkYear(year);
		this.month = month;
		this.day = day;
	}
	public CustomDate(int year, int month) {
		this.year = checkYear(year);
		this.month = month;
		this.day = 1;
	}
	public CustomDate(int year) {
		this.year = checkYear(year);
		this.month = 1;
		this.day = 1;
	}
	public CustomDate() {// 默认初始化的日期为1991-01-01
		this.year = 1991;
		this.month = 1;
		this.day = 1;
	}
	public String toString() {
		return "" + this.year
				+ (this.month > 9 ? "" + this.month : "0" + this.month)// 月以MM的形式表示
				+ (this.day > 9 ? "" + this.day : "0" + this.day);// 日以dd的形式表示
	}
	public boolean equals(CustomDate md) {
		return ((md.day == this.day) && (md.month == this.month) && (md.year == this.year));
	}
}
// 阳历日期类,继承自定义日期
class Solar extends CustomDate {
	private static int checkMonth(int month) {// 检查月份是否越有效范围
		if (month > 12) {
			System.out.println("输入的月份越界, 默认月份为12月 ");
			return 12;
		} else if (month < 1) {
			System.out.println("输入的月份越界, 默认月份为1月");
			return 1;
		} else
			return month;
	}
	private static int checkDay(int year, int month, int day) {// 检查日期是否越有效范围
		int iMonthDays = MutualConversion.getSolarMonthOfDays(year, month);
		if (day > iMonthDays) {
			System.out.println("输入的日期越界, 默认日期为 " + iMonthDays + " ");
			return iMonthDays;
		} else if (day < 1) {
			System.out.println("输入的日期越界, 默认日期为1号");
			return 1;
		} else
			return day;
	}
	// SolarDate类的构造方法
	public Solar(int year, int month, int day) {
		super(year);
		this.month = checkMonth(month);
		this.day = checkDay(this.year, this.month, day);
	}
	public Solar(int year, int month) {
		super(year);
		this.month = checkMonth(month);
	}
	public Solar(int year) {
		super(year);
	}
	public Solar() {
		super();
	}
	// 以字符串的形式输出
	public String toString() {
		return "" + this.year
				+ (this.month > 9 ? "-" + this.month : "-0" + this.month)
				+ (this.day > 9 ? "-" + this.day : "-0" + this.day);
	}
	// 获取输入的年月日是星期几
	public CustomWeek toWeek() {
		int days = 0;
		for (int i = 1901; i < year; i++) {
			if (MutualConversion.isLeapYearOfSolar(i))
				days += 366;
			else
				days += 365;
		}
		days += MutualConversion.L_getOffsetOfDays(year, month, day);
		return new CustomWeek((days + 2) % 7);
	}
	public Lunar dateToLunar() {// 将输入日期转换成农历日期
		int year, month, day, iDate;
		Lunar ld;
		iDate = Integer.parseInt(MutualConversion.solarToLundar(this.year,
				this.month, this.day));
		year = iDate / 10000;
		month = iDate % 10000 / 100;
		day = iDate % 100;
		ld = new Lunar(year, month, day);
		return ld;
	}
	public void getDate(int year, int month) {
		Calendar calendar = Calendar.getInstance();// 获取一个Calendar对象
		int count = 0;// 定义一个计数变量
		calendar.set(Calendar.YEAR, year);// 设置年份
		calendar.set(Calendar.MONTH, month - 1);// 设置月份
		calendar.set(Calendar.DATE, 0);// 设置日期
		int days = MutualConversion.getSolarMonthOfDays(year, month);
		;
		System.out.println(year + " 年 " + month + " 月 份 的 万 年 历 如 下:");
		System.out.println("星期日\t\t星期一\t\t星期二\t\t星期三\t\t星期四\t\t星期五\t\t星期六");
		while (count < days) {
			calendar.add(Calendar.DAY_OF_MONTH, 1);// 设置添加日历的周期为1
			int day = calendar.getTime().getDay();// 获取日历的星期几表示数,例如:0:表示星期日
			if (count == 0) {// 根据星期几来决定输入几个tab
				for (int i = 0; i < day; i++) {
					System.out.print("\t\t");
				}
			}
			if (day == 0) {// 如果是周日了则换行
				System.out.println();
			}
			String time = MutualConversion.solarToLundar(year, month, calendar
					.getTime().getDate());
			String[] str = time.split("-");
			Lunar la = new Lunar(Integer.parseInt(str[0]), Integer
					.parseInt(str[1]), Integer.parseInt(str[2]));
			String name = la.toString(0);
			System.out.print(calendar.getTime().getDate() + " ");// 获取日历中日期数
			System.out.print(name + "\t");// 获取日历中日期数
			count++;
		}
	}
}
// 农历日期类,继承自定义日期类
class Lunar extends CustomDate {
	private String upperFigure[] = { "零", "一", "二", "三", "四", "五", "六", "七",
			"八", "九", "十" };
	private static int checkDay(int year, int month, int day) {// 检查日期是否越有效范围
		int iMonthDays = MutualConversion.getSolarMonthOfDays(year, month);
		if (day > iMonthDays) {
			System.out.println("输入的日期越界, 默认日期为 " + iMonthDays + " ");
			return iMonthDays;
		} else if (day < 1) {
			System.out.println("输入的日期越界, 默认日期为1号");
			return 1;
		} else
			return day;
	}
	private static int checkMonth(int year, int month) {// 检查月份是否越有效范围
		if ((month > 12)
				&& (month == MutualConversion.L_getLeapMonth(year) + 12)) {
			return month;
		} else if (month > 12) {
			System.out.println("输入的月份越界, 默认月份为12月 ");
			return 12;
		} else if (month < 1) {
			System.out.println("输入的月份越界, 默认月份为1月");
			return 1;
		} else
			return month;
	}
	// LunarDate类的构造方法
	public Lunar(int year, int month, int day) {
		super(year);
		this.month = checkMonth(this.year, month);
		this.day = checkDay(this.year, this.month, day);
	}
	public Lunar(int year, int month) {
		super(year);
		this.month = checkMonth(this.year, month);
	}
	public Lunar(int year) {
		super(year);
	}
	public Lunar() {
		super();
	}
	// 以字符串的形式输出
	public String toString(int n) {
		String sCalendar = "";
		if (n == 1) {
			sCalendar += "农历" + upperFigure[year / 1000]
					+ upperFigure[year % 1000 / 100]
					+ upperFigure[year % 100 / 10] + upperFigure[year % 10]
					+ "(" + toChineseEra() + ")年";
		}
		if (month > 12) {
			month -= 12;
			sCalendar += "闰";
		}
		if (month == 12)
			sCalendar += "腊月";
		else if (month == 11)
			sCalendar += "冬月";
		else if (month == 1)
			sCalendar += "正月";
		else
			sCalendar += upperFigure[month] + "月";
		if (day > 29)
			sCalendar += "三十";
		else if (day > 20)
			sCalendar += "二十" + upperFigure[day % 20];
		else if (day == 20)
			sCalendar += "二十";
		else if (day > 10)
			sCalendar += "十" + upperFigure[day % 10];
		else
			sCalendar += "初" + upperFigure[day];
		return sCalendar;
	}
	public CnWeek toWeek() {// 获取输入日期的星期几
		int days = 0;
		for (int i = 1901; i < year; i++)
			days += MutualConversion.getLunarYear(i);
		days += MutualConversion.getOffsetOfDays(year, month, day);
		return new CnWeek((days + 2) % 7);
	}
	public ChineseEra toChineseEra() {
		return new ChineseEra(year);
	}
	public Solar toSolarDate() {// 转换成阳历
		int year, month, day, iDate;
		Solar sd;
		iDate = Integer.parseInt(MutualConversion.lundarToSolar(this.year,
				this.month, this.day));
		year = iDate / 10000;
		month = iDate % 10000 / 100;
		day = iDate % 100;
		sd = new Solar(year, month, day);
		return sd;
	}
}
class CnWeek extends CustomWeek {// Week的子类
	private String sCnWeek[] = { "日", "一", "二", "三", "四", "五", "六" };
	// 调用父类的构造方法
	public CnWeek() {
		super();
	}
	public CnWeek(int week) {
		super(week);
	}
	public String toString() {
		return "星期" + sCnWeek[this.week];
	}
}
// 用天干地支形式表示农历年
class ChineseEra {
	int year;
	String[] westernNotation = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬",
			"癸" };
	String[] chineseEraNotation = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未",
			"申", "酉", "戌", "亥" };
	public ChineseEra() {
		int year = 1991;
	}
	public ChineseEra(int year) {
		if ((year < 2050) && (year > 1901))
			this.year = year;
		else
			this.year = 1991;
	}
	public String toString() {
		int temp;
		temp = Math.abs(year - 1924);
		return westernNotation[temp % 10] + chineseEraNotation[temp % 12];
	}
}

 

  11.4 Formatter类的使用

  实例199 时间格式转换符的使用

package Chapter11.format;

import java.util.Formatter;

public class FormatterUsage {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Object[] ob = new Object[2];// 创建Object数组
		// 给数组赋值
		ob[0] = Integer.valueOf(51);
		ob[1] = Integer.valueOf(1293);
		Formatter fmt = null;
		System.out.println("第一种输出方式:");
		fmt = new Formatter(); // 以默认的存储区为目标,创建对象
		Object[] ob1 = new Object[2];
		ob1[0] = Double.valueOf(1112.12675456);
		ob1[1] = Double.valueOf(0.1258989);
		fmt.format("输出到自带存储区,每个输出项占8个字符位:%4.3f %5.2f\n", ob1); // 格式化输出数据,输出到自己的存储区
		System.out.print(fmt); // 再从对象的存储区中输出到屏幕
		System.out.println("\n第二种输出方式:");
		fmt = new Formatter(System.out); // 以标准输出设备为目标,创建对象
		fmt.format("直接输出,每个输出项占5个字符位:%5d%5d\n\n", ob); // 格式化输出数据,并输出到标准输出设备
		System.out.println("第三种输出方式:");
		StringBuffer buf = new StringBuffer();
		fmt = new Formatter(buf); // 以指定的字符串为目标,创建对象
		fmt.format("输出到指定的缓冲区,每个输出项占8个字符位:%8d%8d\n\n", ob); // 格式化输出数据,输出到buf中
		System.out.print(buf); // 再从buf中输出到屏幕

	}

}

 

  实例200 数据格式转换符的使用

package Chapter11.format;

import java.util.Formatter;

public class FormatterUsage {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Object[] ob = new Object[2];// 创建Object数组
		// 给数组赋值
		ob[0] = Integer.valueOf(51);
		ob[1] = Integer.valueOf(1293);
		Formatter fmt = null;
		System.out.println("第一种输出方式:");
		fmt = new Formatter(); // 以默认的存储区为目标,创建对象
		Object[] ob1 = new Object[2];
		ob1[0] = Double.valueOf(1112.12675456);
		ob1[1] = Double.valueOf(0.1258989);
		fmt.format("输出到自带存储区,每个输出项占8个字符位:%4.3f %5.2f\n", ob1); // 格式化输出数据,输出到自己的存储区
		System.out.print(fmt); // 再从对象的存储区中输出到屏幕
		System.out.println("\n第二种输出方式:");
		fmt = new Formatter(System.out); // 以标准输出设备为目标,创建对象
		fmt.format("直接输出,每个输出项占5个字符位:%5d%5d\n\n", ob); // 格式化输出数据,并输出到标准输出设备
		System.out.println("第三种输出方式:");
		StringBuffer buf = new StringBuffer();
		fmt = new Formatter(buf); // 以指定的字符串为目标,创建对象
		fmt.format("输出到指定的缓冲区,每个输出项占8个字符位:%8d%8d\n\n", ob); // 格式化输出数据,输出到buf中
		System.out.print(buf); // 再从buf中输出到屏幕

	}

}

 

  11.5 System类的使用

  实例201 记录程序执行的时间

package Chapter11.system;

public class RecordTimes {

	/**
	 * @param args
	 */
	public static void main(String args[]) {
		try {
			long start = System.currentTimeMillis();// 记录程序开始执行时的时间
			System.out.println("开始执行的时间为:" + start);
			Thread.sleep(3000);
			long end = System.currentTimeMillis();// 记录程序结束执行时的时间
			System.out.println("结束执行的时间为: " + end);
			System.out.println("共执行了:" + (end - start) + "毫秒");// 结束时间-开始时间=执行了的时间
		} catch (InterruptedException el) {
			el.printStackTrace();
		}
	}

}

 

  实例202 程序的退出

package Chapter11.system;

public class Exit extends Thread {

	/**
	 * @param args
	 */
	public static void main(String args[]) {
		Exit exit = new Exit();
		Thread th = Thread.currentThread();// 获取主线程
		exit.start();
		System.out.println("主线程开始运行。。。");
		try {
			System.out.println("休眠开始~~");
			th.sleep(1000);// 令线程暂停运行
		} catch (InterruptedException el) {
			el.printStackTrace();
		}
		System.out.println("主线程运行结束");
	}

	public void run() { // 线程类的抽象方法
		System.out.println("线程正在运行中,调用System.exit(0)方法,强制JVM退出!!");
		System.exit(0);// 强制JVM退出
	}
}

 

  实例203 获取程序运行环境的信息

package Chapter11.system;

public class INFO {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// 通过调用System类的getProperty方法来获取相应的属性值
		System.out.println("用户的账户名称:" + System.getProperty("user.name"));
		System.out.println("当前用户工作目录:" + System.getProperty("user.dir"));
		System.out.println("用户的home路径:" + System.getProperty("user.home"));
		System.out.println("类所在的路径:" + System.getProperty("java.class.path"));
		System.out.println("操作系统的名称:" + System.getProperty("os.name"));
		System.out.println("操作系统的版本:" + System.getProperty("os.version"));
		System.out.println("操作系统的架构:" + System.getProperty("os.arch"));
		System.out.println("虚拟机实现的版本:" + System.getProperty("java.vm.version"));
		System.out.println("虚拟机实现的生产商:" + System.getProperty("java.vm.vendor"));
		System.out.println("默认的临时文件路径:" + System.getProperty("java.io.tmpdir"));
		System.out.println("运行环境规范的名称:"
				+ System.getProperty("java.specification.name"));
		System.out.println("Java类格式化的版本号:"
				+ System.getProperty("java.class.version"));
		System.out.println("Java运行环境的版本:" + System.getProperty("java.version"));
		System.out.println("Java运行环境的生产商:" + System.getProperty("java.vendor"));
		System.out.println("Java的安装路径:" + System.getProperty("java.home"));
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值