曾经做过的40道程序设计课后习题总结(四)
课后习题目录
1 斐波那契数列
2 判断素数
3 水仙花数
4 分解质因数
5 杨辉三角
6 学习成绩查询
7 求最大公约数与最小公倍数
8 完全平方数
9 统计字母、空格、数字和其它字符个数
10 求主对角线之和
11 完数求解
12 求s=a+aa+aaa+aaaa+aa...a的值
13 高度计算
14 乘法口诀
15 无重复三位数
16 菱形打印
17 利润计算
18 第几天判断
19 从小到大输出数列
20 猴子吃桃问题
21 乒乓球比赛
22 求分数之和
23 求阶乘的和
24 递归求法
25 求不多于5的正整数
26 回文判断
27 星期判断
28 插数入数组
29 取整数的任意位
30 按顺序输出数列
31 位置替换
32 字符串排序
33 贷款器
34 通讯录排序
35 闰年判断
36 二元方程求解
37 密码解译
38 DVD查询
39 电子日历
40 万年历
31 位置替换
31.1题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
31.2 源程序
import java.util.Scanner; public class TiHuan { static final int N = 8; public static void main(String[] args) { int[] a = new int[N]; Scanner s = new Scanner(System.in); int index1 = 0, index2 = 0; System.out.println("please input numbers"); for (int i = 0; i < N; i++) { a[i] = s.nextInt(); System.out.print(a[i] + " "); } int max = a[0], min = a[0]; for (int i = 0; i < a.length; i++) { if (a[i] > max) { max = a[i]; index1 = i; } if (a[i] < min) { min = a[i]; index2 = i; } } if (index1 != 0) { int temp = a[0]; a[0] = a[index1]; a[index1] = temp; } if (index2 != a.length - 1) { int temp = a[a.length - 1]; a[a.length - 1] = a[index2]; a[index2] = temp; } System.out.println("after swop:"); for (int i = 0; i < a.length; i++) { System.out.print(a[i] + " "); } } }
31.3 运行结果:
please input numbers 2 2 3 3 4 4 5 5 6 6 7 7 8 8 1 1 after swop: 8 3 4 5 6 7 2 1
32 字符串排序
32.1题目:字符串排序。
32.2 源程序
public class StringSort { public static void main(String[] args) { String temp = null; String[] s = new String[5]; s[0] = "china".toLowerCase(); s[1] = "apple".toLowerCase(); s[2] = "MONEY".toLowerCase(); s[3] = "BOOk".toLowerCase(); s[4] = "yeah".toLowerCase(); /* * for(int i=0; i<s.length; i++) { for(int j=i+1; j<s.length; j++) { * if(s[i].compareToIgnoreCase(s[j]) > 0) { temp = s[i]; s[i] = s[j]; * s[j] = temp; } } } */ for (int i = 0; i < s.length; i++) { for (int j = i + 1; j < s.length; j++) { if (compare(s[i], s[j]) == false) { temp = s[i]; s[i] = s[j]; s[j] = temp; } } } for (int i = 0; i < s.length; i++) { System.out.println(s[i]); } } static boolean compare(String s1, String s2) { boolean result = true; for (int i = 0; i < s1.length() && i < s2.length(); i++) { if (s1.charAt(i) > s2.charAt(i)) { result = false; break; } else if (s1.charAt(i) < s2.charAt(i)) { result = true; break; } else { if (s1.length() < s2.length()) { result = true; } else { result = false; } } } return result; } }
32.3 运行结果:
apple
book
china
money
yeah
33 贷款器
题目:编写贷款计算程序,根据给定的贷款金额、年利率及贷款期限,计算月支付金额及总支付金额。
33.1 源程序
package example; import javax.swing.*; import java.text.*; public class daikuanqi { public static void main(String[] args) { final int MONTHS_IN_YEAR=12; double loanAmount,annualInterestRate; double monthlyPayment,totalPayment; double monthlyInterestRate; int loanPeriod; int numberOfPayments; String inputStr; DecimalFormat df=new DecimalFormat("0.00"); //get input values inputStr=JOptionPane.showInputDialog(null,"贷款金额(精确到美分,如15000.00):"); loanAmount=Double.parseDouble(inputStr); inputStr=JOptionPane.showInputDialog(null,"年利率(百分比,如9.5):"); annualInterestRate=Double.parseDouble(inputStr); inputStr=JOptionPane.showInputDialog(null,"贷款期限(年份,如30):"); loanPeriod=Integer.parseInt(inputStr); monthlyInterestRate=annualInterestRate/MONTHS_IN_YEAR/100; numberOfPayments=loanPeriod*MONTHS_IN_YEAR; monthlyPayment=(loanAmount*monthlyInterestRate)/(1-Math.pow(1/(1+monthlyInterestRate),numberOfPayments)); totalPayment=monthlyPayment*numberOfPayments; System.out.println("贷款金额:$ "+loanAmount); System.out.println("年利率: "+annualInterestRate+"%"); System.out.println("贷款期限: "+loanPeriod); System.out.println(""); System.out.println("月付款金额:$ "+df.format(monthlyPayment)); System.out.println("总付款金额:$ "+df.format(totalPayment)); System.out.println(""); } }
33.2 程序运行结果:
输出: 贷款金额:$ 10000.0 年利率: 10.0% 贷款期限: 10 月付款金额:$ 132.15 总付款金额:$ 15858.09
34 通讯录排序
34.1 题目:对通讯录排序。要求:扩展AddressBook类,为其引入一个排序程序。以三种不同的实现方法使新的AddressBook类可以Person对象排序(按姓名的字母表顺序或者年龄递增的顺序)。
34.2 源程序
package example12; import javax.swing.*; class example12 { public static void main(String[] args) { example12 tester = new example12(); tester.start(); } private void start() { String[] name = { "ape", "cat", "bee", "bat", "eel", "dog", "gnu", "yak", "fox", "cow", "hen", "tic", "man" }; Person p; AddressBook ab; int version = Integer.parseInt(JOptionPane.showInputDialog(null, "有三种方法可以实现Person对象排序,请输入数字(1-3):")); switch (version) { case 1: ab = new AddressBookVer1(); break; case 2: ab = new AddressBookVer2(); break; case 3: ab = new AddressBookVer3(); break; default: ab = new AddressBookVer1(); break; } System.out.println("输入数据:"); for (int i = 0; i < name.length; i++) { p = new Person(name[i], random(10, 50), random(0, 1) == 0 ? 'M' : 'F'); // if(random(0,1) ==0) 'M' else 'F' ab.add(p); System.out.println(p.toString()); } System.out.println(" "); Person[] sortedlist = ab.sort(Person.AGE); System.out.println("按年龄排序:"); for (int i = 0; i < sortedlist.length; i++) { System.out.println(sortedlist[i].toString()); } System.out.println(" "); sortedlist = ab.sort(Person.NAME); System.out.println("按姓名排序:"); for (int i = 0; i < sortedlist.length; i++) { System.out.println(sortedlist[i].toString()); } } private int random(int low, int high) { return (int) Math.floor(Math.random() * (high - low + 1)) + low; } } AddressBook类: package example12; interface AddressBook { public void add( Person newPerson ); public boolean delete( String searchName ); public Person search( String searchName ); public Person[ ] sort ( int attribute ); } Person类: package example12; class Person { public static final int NAME = 0; public static final int AGE = 1; private static final int LESS = -1; private static final int EQUAL = 0; private static final int MORE = 1; private static int compareAttribute; private String name; private int age; private char gender; static { compareAttribute = NAME; } public Person() { this("Not Given", 0, 'U'); } public Person(String name, int age, char gender) { this.age = age; this.name = name; this.gender = gender; } public static void setCompareAttribute( int attribute ) { compareAttribute = attribute; } public int compareTo( Person person, int attribute ) { int comparisonResult; if ( attribute == AGE ) { int p2age = person.getAge( ); if (this.age < p2age) { comparisonResult = LESS; } else if (this.age == p2age) { comparisonResult = EQUAL; } else { assert this.age > p2age; comparisonResult = MORE; } } else { //compare the name using the String class抯 //compareTo method String p2name = person.getName( ); comparisonResult = this.name.compareTo(p2name); } return comparisonResult; } public int compareTo( Person person ) { return compareTo(person, compareAttribute); } public int getAge( ) { return age; } public char getGender( ) { return gender; } public String getName( ) { return name; } public void setAge( int age ) { this.age = age; } public void setGender( char gender ) { this.gender = gender; } public void setName( String name ) { this.name = name; } public String toString( ) { return this.name + " " + this.age + " " + this.gender; } } AddressBookVer1类: package example12; class AddressBookVer1 implements AddressBook { private static final int DEFAULT_SIZE = 25; private static final int NOT_FOUND = -1; private Person[] entry; private int count; public AddressBookVer1( ) { this( DEFAULT_SIZE ); } public AddressBookVer1( int size ) { count = 0; if (size <= 0 ) { //invalid data value, use default throw new IllegalArgumentException("Size must be positive"); } entry = new Person[size]; // System.out.println("array of "+ size + " is created."); //TEMP } public void add(Person newPerson) { if (count == entry.length) { //no more space left, enlarge( ); //create a new larger array } //at this point, entry refers to a new larger array entry[count] = newPerson; count++; } public boolean delete( String searchName ) { boolean status; int loc; loc = findIndex( searchName ); if (loc == NOT_FOUND) { status = false; } else { //found, pack the hole entry[loc] = entry[count-1]; status = true; count--; //decrement count, //since we now have one less element } return status; } public Person search( String searchName ) { Person foundPerson; int loc = 0; while ( loc < count && !searchName.equals( entry[loc].getName() ) ) { loc++; } if (loc == count) { foundPerson = null; } else { foundPerson = entry[loc]; } return foundPerson; } public Person[ ] sort ( int attribute ) { if (!(attribute == Person.NAME || attribute == Person.AGE) ) { throw new IllegalArgumentException( ); } Person[ ] sortedList = new Person[ count ]; Person p1, p2, temp; //copy references to sortedList for (int i = 0; i < count; i++) { sortedList[i] = entry[i]; } //set the comparison attribute entry[0].setCompareAttribute( attribute ); //begin the bubble sort on sortedList int bottom, comparisonResult; boolean exchanged = true; bottom = sortedList.length - 2; while ( exchanged ) { exchanged = false; for (int i = 0; i <= bottom; i++) { p1 = sortedList[i]; p2 = sortedList[i+1]; // comparisonResult = p1.compareTo( p2, attribute ); comparisonResult = p1.compareTo( p2 ); if ( comparisonResult > 0 ) { //p1 is 鎲�rger锟� //than p2, so sortedList[i] = p2; //exchange sortedList[i+1] = p1; exchanged = true; //exchange is made } } bottom--; } return sortedList; } private void enlarge( ) { //create a new array whose size is 150% of //the current array int newLength = (int) (1.5 * entry.length); Person[] temp = new Person[newLength]; //now copy the data to the new array for (int i = 0; i < entry.length; i++) { temp[i] = entry[i]; } //finally set the variable entry to point to the new array entry = temp; // System.out.println("Inside the method enlarge"); //TEMP // System.out.println("Size of a new array: " + entry.length); //TEMP } private int findIndex( String searchName ) { int loc = 0; while ( loc < count && !searchName.equals( entry[loc].getName() ) ) { loc++; } if (loc == count) { loc = NOT_FOUND; } return loc; } } AddressBookVer2类: package example12; import java.util.*; class AddressBookVer2 implements AddressBook { private static final int DEFAULT_SIZE = 25; private static final int NOT_FOUND = -1; private Person[] entry; private int count; public AddressBookVer2( ) { this( DEFAULT_SIZE ); } public AddressBookVer2(int size) { count = 0; if (size <= 0 ) { //invalid data value, use default throw new IllegalArgumentException("Size must be positive"); } entry = new Person[size]; // System.out.println("array of "+ size + " is created."); //TEMP } public void add( Person newPerson ) { if (count == entry.length) { //no more space left, enlarge( ); //create a new larger array } //at this point, entry refers to a new larger array entry[count] = newPerson; count++; } public boolean delete( String searchName ) { boolean status; int loc; loc = findIndex( searchName ); if (loc == NOT_FOUND) { status = false; } else { //found, pack the hole entry[loc] = entry[count-1]; status = true; count--; //decrement count, //since we now have one less element } return status; } public Person search( String searchName ) { Person foundPerson; int loc = 0; while ( loc < count && !searchName.equals( entry[loc].getName() ) ) { loc++; } if (loc == count) { foundPerson = null; } else { foundPerson = entry[loc]; } return foundPerson; } public Person[ ] sort ( int attribute ) { if (!(attribute == Person.NAME || attribute == Person.AGE) ) { throw new IllegalArgumentException( ); } Person[ ] sortedList = new Person[ count ]; //copy references to sortedList for (int i = 0; i < count; i++) { sortedList[i] = entry[i]; } Arrays.sort(sortedList, getComparator(attribute)); return sortedList; } private void enlarge( ) { //create a new array whose size is 150% of //the current array int newLength = (int) (1.5 * entry.length); Person[] temp = new Person[newLength]; //now copy the data to the new array for (int i = 0; i < entry.length; i++) { temp[i] = entry[i]; } //finally set the variable entry to point to the new array entry = temp; // System.out.println("Inside the method enlarge"); //TEMP // System.out.println("Size of a new array: " + entry.length); //TEMP } private int findIndex( String searchName ) { int loc = 0; while ( loc < count && !searchName.equals( entry[loc].getName() ) ) { loc++; } if (loc == count) { loc = NOT_FOUND; } return loc; } private Comparator getComparator(int attribute) { Comparator comp = null; if (attribute == Person.AGE) { comp = new AgeComparator( ); } else { assert attribute == Person.NAME: "Attribute not recognized for sorting"; comp = new NameComparator( ); } return comp; } class AgeComparator implements Comparator { private final int LESS = -1; private final int EQUAL = 0; private final int MORE = 1; public int compare(Object p1, Object p2) { int comparisonResult; int p1age = ((Person)p1).getAge( ); int p2age = ((Person)p2).getAge( ); if (p1age < p2age) { comparisonResult = LESS; } else if (p1age == p2age) { comparisonResult = EQUAL; } else { assert p1age > p2age; comparisonResult = MORE; } return comparisonResult; } } class NameComparator implements Comparator { public int compare(Object p1, Object p2) { String p1name = ((Person)p1).getName( ); String p2name = ((Person)p2).getName( ); return p1name.compareTo(p2name); } } } AddressBookVer3类: package example12; import java.util.*; class AddressBookVer3 implements AddressBook { private static final int DEFAULT_SIZE = 25; private Map entry; public AddressBookVer3( ) { this( DEFAULT_SIZE ); } public AddressBookVer3(int size) { entry = new HashMap(size); // System.out.println("array of "+ size + " is created."); //TEMP } public void add( Person newPerson ) { entry.put(newPerson.getName(), newPerson); } public boolean delete( String searchName ) { boolean status; Person p = (Person) entry.remove(searchName); if (p == null) { status = false; } else { status = true; } return status; } public Person search( String searchName ) { return (Person) entry.get(searchName); } public Person[ ] sort ( int attribute ) { if (!(attribute == Person.NAME || attribute == Person.AGE) ) { throw new IllegalArgumentException( ); } Person[ ] sortedList = new Person[entry.size()]; entry.values().toArray(sortedList); Arrays.sort(sortedList, getComparator(attribute)); return sortedList; } private Comparator getComparator(int attribute) { Comparator comp = null; if (attribute == Person.AGE) { comp = new AgeComparator( ); } else { assert attribute == Person.NAME: "Attribute not recognized for sorting"; comp = new NameComparator( ); } return comp; } class AgeComparator implements Comparator { private final int LESS = -1; private final int EQUAL = 0; private final int MORE = 1; public int compare(Object p1, Object p2) { int comparisonResult; int p1age = ((Person)p1).getAge( ); int p2age = ((Person)p2).getAge( ); if (p1age < p2age) { comparisonResult = LESS; } else if (p1age == p2age) { comparisonResult = EQUAL; } else { assert p1age > p2age; comparisonResult = MORE; } return comparisonResult; } } class NameComparator implements Comparator { public int compare(Object p1, Object p2) { String p1name = ((Person)p1).getName( ); String p2name = ((Person)p2).getName( ); return p1name.compareTo(p2name); } } }
34.3 运行结果:
35 闰年判断
35.1题目:判断某年是否为闰年
35.2 源程序
import java.util.Scanner; import javax.swing.JOptionPane; public class RunNian { public static void main(String args[]) { Scanner input = new Scanner(System.in); System.out.print("输入年份: "); int year = input.nextInt(); if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { // 输出某年是闰年 System.out.println(year + "年是闰年"); } else { // 输出某年是平年 System.out.println(year + "年是平年"); } } }
35.3 运行结果:
输入年份: 1989 1989年是平年 输入年份: 2000 2000年是闰年
36 二元方程求解
36.1题目:求方程的解。
36.2 源程序
import java.util.Scanner; import javax.swing.JOptionPane; public class Quetation { public static void main(String args[]){ double a,b,c,disc,x1,x2,realpart,imagpart; Scanner scanner=new Scanner(System.in); System.out.print("输入a的值:"); a=scanner.nextDouble(); System.out.print("输入b的值:"); b=scanner.nextDouble(); System.out.print("输入c的值:"); c=scanner.nextDouble(); System.out.print("这个方程"); if(Math.abs(a)<=Math.pow(10, -6)) System.out.print("不是一元二次方程"); else{ disc=b*b-4*a*c; if(Math.abs(disc)<=Math.pow(10, -6)) System.out.println("有两个相等实根:"+-b/(2*a)); else if(disc>Math.pow(10, -6)){ x1=(-b+Math.sqrt(disc))/(2*a); x2=(-b+Math.sqrt(disc))/(2*a); System.out.println("有两个不等实根:"+x1+"和"+x2); } else{ realpart=-b/(2*a); imagpart=Math.sqrt(-disc)/(2*a); System.out.println("有两个共轭复根:"); System.out.println(realpart+"+"+imagpart+"i"); System.out.println(realpart+"-"+imagpart+"i"); } } } }
36.3 运行结果:
输入a的值:1 输入b的值:2 输入c的值:1 这个方程有两个相等实根:-1.0 输入a的值:1 输入b的值:2 输入c的值:2 这个方程有两个共轭复根: -1.0+1.0i -1.0-1.0i 输入a的值:2 输入b的值:6 输入c的值:1 这个方程有两个不等实根:-0.17712434446770464和-0.17712434446770464
37 密码解译
37.1题目:为使电文保密,往往按一定规律将其转换成密码,收报人再按约定的规律将其译回原文。例如,可以按一下规律将电文变成密码:
将字母A变成字母E,a变成e,即变成其后的第4个字母,W变成A,X变成B,Y变成C,Z变成C。字母按上述规律转换,非字母字符不变。
37.2 源程序
import java.util.Scanner; import javax.swing.JOptionPane; public class Code { public static void main(String[] args) { String string; int numberOfString; char letter; string = JOptionPane.showInputDialog(null, "输入字符串:"); numberOfString = string.length(); for (int i = 0; i < numberOfString; i++) { letter = string.charAt(i); if ((letter >= 'a' && letter <= 'z') || (letter >= 'A' && letter <= 'Z')) { letter = (char) (letter + 4); if ((letter > 'Z' && letter <= 'Z' + 4) || letter >= 'z') { letter = (char) (letter - 26); } System.out.print(letter); } } } }
37.3 运行结果:
Glmre
38 DVD查询
38.1 源程序
1 DVDMgr.java import java.util.Scanner; public class DVDMgr { /** * 创建DVD集 */ DVDSet dvd = new DVDSet(); /** * 初始化数据 */ public void setData() { dvd.initial(); } /** * 显示菜单 */ public void startMenu() { System.out.println("欢 迎 使 用 MiniDVD Mgr 1.0"); System.out.println("--------------------------------------------"); System.out.println("1. 查 看 DVD"); System.out.println("2. 借 出 DVD"); System.out.println("3. 退 出 MiniDVD Mgr"); System.out.println("-------------------------------------------- "); System.out.print("请选择: "); Scanner input = new Scanner(System.in); int choice = input.nextInt(); switch (choice) { case 1: search(); break; case 2: lend(); break; case 3: System.out.println(" 欢 迎 使 用!"); break; } } /** * 查询所有DVD信息 */ public void search() { System.out.println("MyDVD Mgr 1.0 ---> 查询DVD "); for (int i = 0; i < dvd.name.length; i++) { if (dvd.name[i] == null) { break; } else if (dvd.state[i] == 0) { System.out.println("<<" + dvd.name[i] + ">>" + " 已借出"); } else if (dvd.state[i] == 1) { System.out.println("<<" + dvd.name[i] + ">>"); } } System.out.println("--------------------------------"); returnMain(); } /** * 借出DVD */ public void lend() { System.out.println("MyDVD Mgr 1.0 ---> 借出DVD "); Scanner input = new Scanner(System.in); System.out.print("请输入DVD名称: "); String want = input.next(); // 要借出的DVD名称 for (int i = 0; i < dvd.name.length; i++) { if (dvd.name[i] == null) { // 查询完所有DVD信息,跳出 System.out.println("操作不成功:没有匹配!"); break; } else if (dvd.name[i].equals(want) && dvd.state[i] == 1) { // 找到匹配,跳出 dvd.state[i] = 0; System.out.println("操作成功!"); break; } } System.out.println("------------------------------------"); returnMain(); } /** * 返回主菜单 */ public void returnMain() { Scanner input = new Scanner(System.in); System.out.print("输入0返回 "); if (input.nextInt() == 0) { startMenu(); } else { System.out.println("输入错误, 异常终止!"); } } /** * 入口程序 * * @param args */ public static void main(String[] args) { DVDMgr mgr = new DVDMgr(); mgr.setData(); // 加载数据 mgr.startMenu(); } } 2 DVDSet源程序 public class DVDSet { String[] name = new String[50]; //数组1存储DVD名称数组 int[] state = new int[50]; //数组2存储DVD借出状态:0已借出/1可借 public void initial(){ /*DVD1:罗马假日*/ name[0] = "罗马假日"; state[0] = 0; /*DVD2: 越狱*/ name[1] = "越狱"; state[1] = 1; /*DVD3: 浪漫满屋*/ name[2] = "浪漫满屋"; state[2] = 1; } }
38.2 运行结果:
欢 迎 使 用 MiniDVD Mgr 1.0 -------------------------------------------- 1. 查 看 DVD 2. 借 出 DVD 3. 退 出 MiniDVD Mgr -------------------------------------------- 请选择: 1 MyDVD Mgr 1.0 ---> 查询DVD <<罗马假日>> 已借出 <<越狱>> <<浪漫满屋>> -------------------------------- 输入0返回 0 欢 迎 使 用 MiniDVD Mgr 1.0 -------------------------------------------- 1. 查 看 DVD 2. 借 出 DVD 3. 退 出 MiniDVD Mgr -------------------------------------------- 请选择: 2 MyDVD Mgr 1.0 ---> 借出DVD 请输入DVD名称: 越狱 操作成功! ------------------------------------ 输入0返回 0 欢 迎 使 用 MiniDVD Mgr 1.0 -------------------------------------------- 1. 查 看 DVD 2. 借 出 DVD 3. 退 出 MiniDVD Mgr -------------------------------------------- 请选择: 3 欢 迎 使 用!
39 电子日历
39.1 源程序
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class Xiaorili extends JApplet { // ================================================== /* 定义全局变量 */ public static final Color background = Color.white;// 背景色 public static final Color foreground = Color.black;// 前景色 public static final Color headerBackground = Color.DARK_GRAY;// 星期 public static final Color headerForeground = Color.white;// 星期前景色 public static final Color selectedBackground = Color.green;// 选中背景色 public static final Color selectedForeground = Color.white;// 选中前景色 public static final String WeekSun = "星期日"; // 星期标签名称 public static final String WeekMon = "星期一"; public static final String WeekTue = "星期二"; public static final String WeekWed = "星期三"; public static final String WeekThu = "星期四"; public static final String WeekFri = "星期五"; public static final String WeekSat = "星期六"; private JPanel MainPanel;// 日历面板 private JLabel yearsLabel;// “年份”标签 private JSpinner yearsSpinner;// 年份组合框 private JLabel monthsLabel;// “月份”标签 private JComboBox monthsComboBox; // 12月份下拉框 private JLabel textLabel;// 标题显示标签 private JLabel InfoLabel;// 个人信息显示标签 private JTable daysTable; // 日表格 private AbstractTableModel daysModel;// 天单元表格 private Calendar calendar;// 日历对象 // ================================================== /* 函数定义 */ public Xiaorili() {// 构造函数 MainPanel = (JPanel) getContentPane(); } public void init() {// 初始化面板界面函数 MainPanel.setLayout(new BorderLayout()); calendar = Calendar.getInstance();// 默认方式,以本地的时区和地区来构造Calendar // -------------------------------------- yearsLabel = new JLabel("年份: "); // 设置年份标签显示 yearsSpinner = new JSpinner();// 构造年份spinner组合框 yearsSpinner.setEditor(new JSpinner.NumberEditor(yearsSpinner, "0000")); yearsSpinner.setValue(new Integer(calendar.get(Calendar.YEAR))); yearsSpinner.addChangeListener(new ChangeListener() {// 注册该组合框的事件监听器 public void stateChanged(ChangeEvent changeEvent) { int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.YEAR, ((Integer) yearsSpinner .getValue()).intValue()); int maxDay = calendar .getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, day > maxDay ? maxDay : day); updateView();// 更新显示 } }); // -------------------------------------- JPanel yearMonthPanel = new JPanel();// 定义年月面板 MainPanel.add(yearMonthPanel, BorderLayout.NORTH);// 添加年月面板到日历面板的南面(最上方) yearMonthPanel.setLayout(new BorderLayout());// 边布局模式 JPanel yearPanel = new JPanel();// 构建年份面板 yearMonthPanel.add(yearPanel, BorderLayout.WEST);// 年份面板添加到年月面板西部(左边) yearPanel.setLayout(new BorderLayout());// 设置年份面板为边布局并添加年份标签和组合框 yearPanel.add(yearsLabel, BorderLayout.WEST); yearPanel.add(yearsSpinner, BorderLayout.CENTER); // -------------------------------------- monthsLabel = new JLabel("月份: "); // 设置月份标签显示 monthsComboBox = new JComboBox();// 月份下拉框 for (int i = 1; i <= 12; i++) { // 构造下拉框的12个月份 monthsComboBox.addItem(new Integer(i)); } monthsComboBox.setSelectedIndex(calendar.get(Calendar.MONTH));// 下拉框当前月份为选中状态 monthsComboBox.addActionListener(new ActionListener() { // 注册月份下拉框的事件监听器 public void actionPerformed(ActionEvent actionEvent) { int day = calendar.get(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.MONTH, monthsComboBox .getSelectedIndex()); int maxDay = calendar .getActualMaximum(Calendar.DAY_OF_MONTH); calendar.set(Calendar.DAY_OF_MONTH, day > maxDay ? maxDay : day); updateView();// 更新面板显示 } }); // -------------------------------------- JPanel monthPanel = new JPanel();// 定义月份面板 yearMonthPanel.add(monthPanel, BorderLayout.EAST);// 添加月份面板到年月面板的东面(右面) monthPanel.setLayout(new BorderLayout());// 月份面板设为边布局方式 monthPanel.add(monthsLabel, BorderLayout.WEST);// 添加月份名称标签到月份面板西面(左面) monthPanel.add(monthsComboBox, BorderLayout.CENTER);// 添加月份下拉框到月份面板中间 // -------------------------------------- textLabel = new JLabel("JAVA小日历"); // 设置标题标签显示 JPanel txetPanel = new JPanel();// 定义标题文本显示面板 yearMonthPanel.add(txetPanel, BorderLayout.CENTER);// 添加标题文本显示面板到年月面板中间 txetPanel.add(textLabel, BorderLayout.CENTER);// 添加标题文本标签到面板 // -------------------------------------- InfoLabel = new JLabel("学号:200841402210姓名:闵光辉 班级:08级计算机科学与技术2班"); // 设置个人信息标签显示 JPanel InfoPanel = new JPanel();// 定义底部个人信息显示面板 MainPanel.add(InfoPanel, BorderLayout.SOUTH);// 添加个人信息显示面板到日历面板南方(下方) InfoPanel.add(InfoLabel);// 添加信息标签文本标签到面板 daysModel = new AbstractTableModel() { // 设置7行7列 public int getRowCount() { return 7; } public int getColumnCount() { return 7; } public Object getValueAt(int row, int column) { if (row == 0) { // 第一行显示星期 return getHeader(column); } row--; Calendar calendar = (Calendar) Xiaorili.this.calendar.clone(); calendar.set(Calendar.DAY_OF_MONTH, 1); int dayCount = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); int moreDayCount = calendar.get(Calendar.DAY_OF_WEEK) - 1; int index = row * 7 + column; int dayIndex = index - moreDayCount + 1; if (index < moreDayCount || dayIndex > dayCount) { return null; } else { return new Integer(dayIndex); } } }; daysTable = new CalendarTable(daysModel, calendar); // 构造日表格 daysTable.setCellSelectionEnabled(true);// 设置表格单元格可选择 daysTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); daysTable.setDefaultRenderer(daysTable.getColumnClass(0), new TableCellRenderer() { public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { String text = (value == null) ? "" : value.toString(); JLabel cell = new JLabel(text); cell.setOpaque(true); // 绘制边界内的所有像素 if (row == 0) { // 第一行显示星期,设置为星期的前景色和背景色 cell.setForeground(headerForeground); cell.setBackground(headerBackground); } else { if (isSelected) { // 日期单元格如果选中,则设置为日期选中的前、背景色 cell.setForeground(selectedForeground); cell.setBackground(selectedBackground); } else { // 设置日期单元格的普通前、背景色 cell.setForeground(foreground); cell.setBackground(background); } } return cell; } }); updateView(); MainPanel.add(daysTable, BorderLayout.CENTER);// 添加日面板到日历面板中间 } // -------------------------------------- public static String getHeader(int index) {// 设置第一行星期的显示 switch (index) { case 0: return WeekSun; case 1: return WeekMon; case 2: return WeekTue; case 3: return WeekWed; case 4: return WeekThu; case 5: return WeekFri; case 6: return WeekSat; default: return null; } } // -------------------------------------- public void updateView() {// 更新面板显示方法 daysModel.fireTableDataChanged(); daysTable.setRowSelectionInterval(calendar.get(Calendar.WEEK_OF_MONTH), calendar.get(Calendar.WEEK_OF_MONTH)); daysTable.setColumnSelectionInterval( calendar.get(Calendar.DAY_OF_WEEK) - 1, calendar .get(Calendar.DAY_OF_WEEK) - 1); } public static class CalendarTable extends JTable {// 表格类 private Calendar calendar; public CalendarTable(TableModel model, Calendar calendar) {// 构造方法 super(model); this.calendar = calendar; } public void changeSelection(int row, int column, boolean toggle, boolean extend) {// 选择表格单元格时 super.changeSelection(row, column, toggle, extend); if (row == 0) {// 选择为第一行(星期)时不改变单元格 return; } Object obj = getValueAt(row, column); if (obj != null) { calendar.set(Calendar.DAY_OF_MONTH, ((Integer) obj).intValue()); } } } }
39.2 运行结果:
40 万年历
40.1 源程序
import java.util.Scanner; public class PrintCalendar7 { public static void main(String[] args) { System.out.println("******************欢 迎 使 用 万 年 历******************"); Scanner input = new Scanner(System.in); System.out.print(" 请选择年份: "); int year = input.nextInt(); System.out.print(" 请选择月份: "); int month = input.nextInt(); System.out.println(); int days = 0; // 存储当月的天数 boolean isRn; /* 判断是否是闰年 */ if (year % 4 == 0 && !(year % 100 == 0) || year % 400 == 0) { // 判断是否为闰年 isRn = true; // 闰年 } else { isRn = false;// 平年 } if(isRn){ System.out.println(year + " 闰年"); } else { System.out.println(year + " 平年"); } /* 计算该月的天数 */ switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 2: if (isRn) { days = 29; } else { days = 28; } break; default: days = 30; break; } System.out.println(month + " 共" + days + "天"); /* 计算输入的年份之前的天数 */ int totalDays = 0; for (int i = 1900; i < year; i++) { /* 判断闰年或平年,并进行天数累加 */ if (i % 4 == 0 && !(i % 100 == 0) || i % 400 == 0) { // 判断是否为闰年 totalDays = totalDays + 366; // 闰年366天 } else { totalDays = totalDays + 365; // 平年365天 } } System.out.println("输入年份距离1900年1月1日的天数:" + totalDays); /* 计算输入月份之前的天数 */ int beforeDays = 0; for (int i = 1; i <= month; i++) { switch (i) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; case 2: if (isRn) { days = 29; } else { days = 28; } break; default: days = 30; break; } if (i < month) { beforeDays = beforeDays + days; } } totalDays = totalDays + beforeDays; // 距离1900年1月1日的天数 System.out.println("输入月份距离1900年1月1日的天数:" + totalDays); System.out.println("当前月份的天数:" + days); /* 计算星期几 */ int firstDayOfMonth; // 存储当月第一天是星期几:星期日为0,星期一~星期六为1~6 int temp = 1 + totalDays % 7; // 从1900年1月1日推算 if (temp == 7) { // 求当月第一天 firstDayOfMonth = 0; // 周日 } else { firstDayOfMonth = temp; } System.out.println("该月第一天是: " + firstDayOfMonth); /* 输出日历 */ System.out.println("星期日 星期一 星期二 星期三 星期四 星期五 星期六"); for (int nullNo = 0; nullNo < firstDayOfMonth; nullNo++) { System.out.print(" "); // 输出空格 } for (int i = 1; i <= days; i++) { System.out.print(i + " "); if ((totalDays + i - 1) % 7 == 5) { // 如果当天为周六,输出换行 System.out.println(); } } }
40.2 运行结果:
******************欢 迎 使 用 万 年 历****************** 请选择年份: 2008 请选择月份: 6 2008 闰年 6 共30天 输入月份距离1900年1月1日的天数:39598 当前月份的天数:30 该月第一天是: 0 星期日 星期一 星期二 星期三 星期四 星期五 星期六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30