“三天打魚,兩天晒網”(java)
阿新 • • 發佈:2019-02-09
題目描述
某人從2010年1月1日起開始“三天打魚兩天晒網”,問這個人在以後的某一天中是“打魚”還是“晒網”。用C或C++語言/java/python實現程式解決問題。
程式流程圖
原始碼
package zuoye;
import java.util.Scanner;
public class Fishinganddrying {
public static void main(String[] args) { boolean a = true; //布林變數a判斷查詢退出 /* * 多次判斷日期是否合法 */ while(a){ Scanner scanner = new Scanner(System.in); //構造一個Scanner類的物件,並且與標準輸入流System.in關聯 System.out.println("請輸入年份:"); int year = scanner.nextInt(); /* * 判斷當前輸入年份是否合法 */ while(year<2009) { System.out.println("輸入的年份不能早於起始年份"); System.out.println("請再次輸入年份:"); year = scanner.nextInt(); //判斷當前輸入年份是否合法,並返回跳過的輸入資訊 } System.out.println("請輸入月份:"); int month = scanner.nextInt(); /* * 判斷當前輸入月份是否合法 */ while( month < 1 | month > 12) { System.out.println("該月份不存在"); System.out.println("請再次輸入月份:"); month = scanner.nextInt(); //判斷當前輸入月份是否合法,並返回跳過的輸入資訊 } System.out.println("請輸入日期:"); int day = scanner.nextInt(); int day0 = getDays(year, month); //判斷輸入的月有多少天 /* * 判斷輸入的日期是否合法 */ while(day > day0 | day < 1 ) { System.out.println("輸入日期不合法"); System.out.println("請再次輸入日期:"); day = scanner.nextInt(); //判斷當前輸入月份是否合法,並返回跳過的輸入資訊 } judge(getAllDays(year, month, day)); /* * 判斷是否退出 */ System.out.println("是否退出?Y/N"); String b = scanner.next(); char c = b.charAt(0); if(c == 'Y') { a = false ; } } } /* * 判斷打魚還是晒網 */ public static void judge(int days) { int x = days % 5; //定義從2010.01.01開始到輸入日期總天數除以5的餘數 if (x >= 1 && x <= 3) { //如果餘數為1、2、3 System.out.println("今天在打魚"); //輸出“今天在打魚” } else if (x == 4 || x == 0) { //如果餘數為0或者4 System.out.println("今天在晒網"); //輸出“今天在晒網” } } /* * 判斷是否是閏年 */ public static boolean runNian(int year) { if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { // 能被4整除且不能被100整除,或者能夠被400整除的是潤年 return true; } return false; } /* * 計算距離輸入日期總天數 */ public static int getAllDays(int year, int month, int day) { int sum = 0; /* * 計算2010-(year-1)之間有多少天 */ for (int i = 2010; i < year; i++) { if (runNian(i)) { sum += 366; //閏年366天 } else { sum += 365; //平年365天 } } sum += getCurrentDays(year, month, day); // 計算本年內該日期之前共有多少天 return sum; } /* * 判斷每月有幾天 */ public static int getDays(int year, int month) { int days = 0; switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: days = 31; break; //1、3、5、7、8、10、12月均有31天 case 4: case 6: case 9: case 11: days = 30; break; //4、6、9、11月均有30天 case 2: if (runNian(year)) { days = 29; //閏年2月份有29天 } else { days = 28; //平年2月份有28天 } break; } return days; //返回天數 } /* * 計算本年內該日期之前共有多少天 */ public static int getCurrentDays(int year, int month, int day) { int sum = 0; for (int i = 1; i < month; i++) { sum += getDays(year, i); } return sum + day; //返回總天數 }
}