java 判断日期为第几天
生活随笔
收集整理的這篇文章主要介紹了
java 判断日期为第几天
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目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();} }總結
以上是生活随笔為你收集整理的java 判断日期为第几天的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: if的条件表达式
- 下一篇: Python:文件的读取、创建、追加、删