生活随笔
收集整理的這篇文章主要介紹了
java简单代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今日學習
java簡單代碼
public class 輸入一到一百的數字判斷是不是質數
{public static void main(String
[] args
) {for (int i
= 1; i
<= 100; i
++) {if (abc(i
)) {System
.out
.println(i
+ "shi zhishu");} elseSystem
.out
.println(i
+ "bushizhishu");}System
.out
.println(abc(10));}public static boolean abc(int kk
) {boolean res
= true;for (int i
= 2; i
<= kk
/ 2; i
++) {if (kk
% i
== 0) {res
= false;break;}}return res
;}
}
public class 輸入日期計算日期在本年的天數
{public static void main(String
[] args
) {Scanner sc
= new Scanner(System
.in
);int year
= 0, months
= 0, date
= 0;while (true) {year
= intputNum(sc
, 1, 3000, "年份");months
= intputNum(sc
, 1, 12, "月份");date
= intputNum(sc
, 1, 30, "日期");boolean bb
= validateDate(year
, months
, date
);if (bb
)break;System
.out
.println("請輸入正確年月日");}System
.out
.println(year
+ "-" + months
+ "-" + date
);}public static boolean validateDate(int year
, int months
, int date
) {boolean res
= false;switch (months
) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:res
= date
>= 1 && date
<= 31;break;case 4:case 6:case 9:case 11:res
= date
>= 1 && date
<= 30;break;case 2:boolean bb
= run(year
);if (bb
)res
= date
<= 29 && date
>= 1;elseres
= date
<= 28 && date
>= 1;break;default:res
= false;break;}return res
;}public static boolean run(int year
) {return (year
% 4 == 0 && year
% 100 != 0) || (year
% 400 == 0);}public static int intputNum(Scanner sc
, int min
, int max
, String str
) {int res
= 0;while (true) {System
.out
.println(str
+ ":");String ss
= sc
.nextLine();try {res
= Integer
.parseInt(ss
);if (res
>= min
&& res
<= max
)break;System
.out
.println("請輸入合理的" + str
+ "值"); } catch (Exception e
) {System
.out
.println("您輸入的日期不合法");}}return res
; }
}
import java
.util
.Scanner
;public class 手寫兔子
{public static void main(String
[] args
) {int months
= 0;Scanner sc
= new Scanner(System
.in
);while (true) {System
.out
.println("月份");String ss
= sc
.nextLine();try {months
= Integer
.parseInt(ss
);if (months
> 0)break;System
.out
.println("請重新輸入月份");} catch (Exception e
) {System
.out
.println("請輸入合法的月份值");}}int num
= tongJi(months
);System
.out
.println(months
+ "月后的兔子數為:" + num
);}public static int tongJi(int months
) {if (months
> 0) {if ((months
== 1) || (months
== 2))return 1;return tongJi(months
- 1) + tongJi(months
- 2);}return 0;}
}
總結
以上是生活随笔為你收集整理的java简单代码的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。