初学java,今天有个日历的扩展作业,就是从键盘输入年份与月份,然后输出该月的日历,求大神指教,谢

2020-10-15 教育 63阅读

你好,这是代码


import java.util.Calendar;
import java.util.Scanner;
/**
 * @author liuxe
 * @since JDK 1.7.0_79
 */
public class CalendarTest {
    public static void main(String[] args) {
        int year = -1;
        int month = -1;
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入年份");
        while (year < 0) {
            try {
                year = scanner.nextInt();
            } catch (Exception ex) {
                year = -1;
                scanner.nextLine();
                System.out.println("输入错误,请输入年份");
            }
        }
        System.out.println("请输入月份");
        while (month < 0) {
            try {
                month = scanner.nextInt();
                if (month < 1 || month > 12) {
                    throw new Exception();
                }
            } catch (Exception ex) {
                month = -1;
                scanner.nextLine();
                System.out.println("输入错误,请输入月份");
            }
        }
        System.out.println("\n日\t一\t二\t三\t四\t五\t六\n");
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, 1);
        int week = calendar.get(Calendar.DAY_OF_WEEK);
        int weekLoop = 0;
        int monthDays = 0;
        //switch结构
        switch (month) {
            case 1:
                monthDays = 31;
                break;
            case 2:
                //判断是不是闰年
                if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
                    monthDays = 29;
                } else {
                    monthDays = 28;
                }
                break;
            case 3:
                monthDays = 31;
                break;
            case 4:
                monthDays = 30;
                break;
            case 5:
                monthDays = 31;
                break;
            case 6:
                monthDays = 30;
                break;
            case 7:
                monthDays = 31;
                break;
            case 8:
                monthDays = 31;
                break;
            case 9:
                monthDays = 30;
                break;
            case 10:
                monthDays = 31;
                break;
            case 11:
                monthDays = 30;
                break;
            default:
                monthDays = 31;
        }
        //for循环
        for (int i = 0 - week + 2; i <= monthDays; i++) {
            if (i <= 0) {
                System.out.print("");
            } else {
                System.out.print(i);
            }
            weekLoop++;
            System.out.print("\t");
            if (weekLoop % 7 == 0) {
                System.out.println();
            }
        }
        System.out.println();
        scanner.close();
    }
}

运行结果:

声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com