本帖最后由 李天甲 于 2012-6-29 10:20 编辑
几个问题,请参见注释- /*
- *目的:若用户输入年和月,则打印出当月的日历
- * 若用户只是输入年,则打印出整年的日历
- *问题所在:只输入年的时候打印不出来,不知为何,求解!
- **/
- import java.util.*;
- import java.io.*;
- class CalendarTest
- {
- static int i;
- static String[] str = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
- public static void getCalendar(int year, int month)
- {
- GregorianCalendar gre = new GregorianCalendar(year, month - 1, 1);
- int days = gre.getActualMaximum(Calendar.DAY_OF_MONTH);
- int startDay = gre.get(Calendar.DAY_OF_WEEK) - 1;
- for (int j = 0; j < str.length; j++)
- {
- System.out.print("\t" + str[j]);
- }
- System.out.println();
- for (i = 0; i < startDay; i++)
- {
- System.out.print("\t");
- }
- for (int day = 1; day <= days; day++)
- {
- System.out.print("\t" + day);
- i++;
- if (i == 7)
- {
- System.out.println();
- i = 0;
- }
- }
- }
- public static void getCalendar(int year)
- {
- for (int i = 1; i <= 12; i++)
- {
- getCalendar(year, i);
- System.out.println();
- }
- }
- public static void main(String[] args) throws Exception
- {
- while (true)
- {
- System.out.println("请输入要查看的年份和月份,格式为:****,**或者****");
- BufferedReader br = new BufferedReader(new InputStreamReader(
- System.in));
- String str1 = br.readLine();
- if (str1.matches("[0-9]")) //判断全是数子,你这里只判断了第一个,应该是[0-9]+ 或者/d+
- {
- int year = Integer.parseInt(str1);
- getCalendar(year);
- System.out.println();
- }
- else
- {
- String[] arr = str1.split(",");
- getCalendar(Integer.parseInt(arr[0]), Integer.parseInt(arr[1])); //因为上面错了,所以下面就空指针了呵呵
- System.out.println();
- }
- }
- }
- }
复制代码 |