题目1
编写程序:从键盘上输入2019年的“month”和“day”,要求通过程序 输出输入的日期为2019年的第几天。
代码1
从12月往下加日期数
package l1_switch_case;
import java.util.Scanner;
public class SwitchDemo4 {public static void main(String[]args){Scanner scanner=new Scanner(System.in);int month=scanner.nextInt();int day=scanner.nextInt();int date=0;/* //方式1:冗余switch (month){case 1:date=day;break;case 2:date=31+day;break;case 3:date=31+28+day;break;case 4:date=31+28+31+day;break;case 5:date=31+28+31+30+day;break;case 6:date=31+28+31+30+31+day;break;case 7:date=31+28+31+30+31+30+day;break;case 8:date=31+28+31+30+31+30+31+day;break;case 9:date=31+28+31+30+31+30+31+31+day;break;case 10:date=31+28+31+30+31+30+31+31+30+day;break;case 11:date=31+28+31+30+31+30+31+31+30+31+day;break;case 12:date=31+28+31+30+31+30+31+31+30+31+30+day;break;}*/switch (month){case 12:date+=31;case 11:date+=31;case 10:date+=30;case 9:date+=31;case 8:date+=31;case 7:date+=30;case 6:date+=31;case 5:date+=30;case 4:date+=31;case 3:date+=28;case 2://加上2月份前面一个月的天数date+=31;case 1:date+=day;}System.out.println(date);scanner.close();}
}
题目2
从键盘分别输入年、月、日,判断这一天是当年的第几天
注:判断一年是否是闰年的标准:
可以被4整除,但不可被100整除
或
可以被400整除
代码2-写法1
package l1_switch_case;import java.util.Scanner;public class SwitchDemo5 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int year = scanner.nextInt();int month = scanner.nextInt();int day = scanner.nextInt();int date = 0;int february = 0;if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {february = 29;} else {february = 28;}switch (month){case 12:date+=31;case 11:date+=31;case 10:date+=30;case 9:date+=31;case 8:date+=31;case 7:date+=30;case 6:date+=31;case 5:date+=30;case 4:date+=31;case 3:date+=february;case 2://加上2月份前面一个月的天数date+=31;case 1:date+=day;}System.out.println(date);scanner.close();}
}
代码2-写法2
package l1_switch_case;import java.util.Scanner;public class SwitchDemo6 {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);int year = scanner.nextInt();int month = scanner.nextInt();int day = scanner.nextInt();int date = 0;switch (month){case 12:date+=31;case 11:date+=31;case 10:date+=30;case 9:date+=31;case 8:date+=31;case 7:date+=30;case 6:date+=31;case 5:date+=30;case 4:date+=31;case 3:if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {date+= 29;} else {date+ = 28;}case 2://加上2月份前面一个月的天数date+=31;case 1:date+=day;}System.out.println(date);scanner.close();}
}