1. 根据年月日判断第多少天
Scanner是SDK1.5新增的一个类,可使用该类创建一个对象。
Scanner scanner=new Scanner(System.in);
然后scanner对象调用下列方法(函数),读取用户在命令行输入的各种数据类型
next.Byte(),nextDouble(),nextFloat,nextInt(),nextLine(),nextLong(),nextShot()
public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("请输入年份");int year = scanner.nextInt();System.out.println("请输入月份:");int month = scanner.nextInt();System.out.println("请输入日:");int day = scanner.nextInt();int sum = 0;//计时器switch (month) {case 12:sum += 30;case 11:sum += 31;case 10:sum += 30;case 9:sum += 31;case 8:sum += 31;case 7:sum += 30;case 6:sum += 31;case 5:sum += 30;case 4:sum += 31;case 3:if (year % 4 == 0 && year % 100 !=0 || year % 400 ==0) {sum+=29;} else {sum+=28;}case 2:sum += 31;case 1:sum += day; }System.out.println("当年的第 "+ sum + " 天");}
输出结果:
2. 根据当前时间判断星期几:
public static String Week(Date date){String[] week = {"星期日","星期一","星期二","星期三","星期四","星期五","星期六"};Calendar calendar= Calendar.getInstance();//Calendar.getInstance()获取指定点时间calendar.setTime(date);int weeks= calendar.get(Calendar.DAY_OF_WEEK) - 1;if(weeks<0){weeks = 0;}System.out.println(week[weeks]);return week[weeks];}public static void main(String[] args) throws Exception {Week(new Date());}
输出结果:
星期日