Java实战

敬请T期待 Lv3

案例一

1.案例:输出某年某个月的天数。年份中指定月份的天数。安全描述:本程序运行时,将屏幕上输出指定8,10,12月的天数技术要点:一年中有12个月,其中1,3,5,2月份的天数为29天,为31天;4,6,9,11月的天数为30天;闰年日其它年份为28天。份能被4整队,但不能被100整除,或者判断当前年份是否为闰年,如果为闰年,则该该年份能被400整除

demo1

Main.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int year,month;
System.out.println("===请输入需要判断的年份===");
Scanner sc = new Scanner(System.in);
year = sc.nextInt();
System.out.println("===请输入需要判断的月份===");
month = sc.nextInt();
while(month <=1 || month >= 12){
System.out.println("===请输入正确的月份===");
month = sc.nextInt();
}
DayInMonth.dayInMonth(year,month);
}
}

DayInMonth.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class DayInMonth {
public static void dayInMonth(int year,int month){
int[] thrity_noe_for_month = {1,3,5,7,8,10,12};
int[] thirth_for_month = {4,6,11};
int[] february ={2};
for(int mo : thrity_noe_for_month){
if(mo == month){
System.out.println(year+"年"+month+"月有31天!");
}
}
for(int mo : thirth_for_month){
if(mo == month){
System.out.println( year+"年"+month+"月有30天!");
}
}
if(month == 2){
if(IsLeapYear.isLeapYear(month)){
System.out.println(year+"年"+month+"月有28天!");
}else{
System.out.println(year+"年"+month+"月有29天!");
}
}
}
}

IsLeapYear.java

1
2
3
4
5
6
7
8
9
public class IsLeapYear {
static boolean isLeapYear(int year) {
//平年
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return true;
}
return false;
}
}

运行结果:

1
2
3
4
5
===请输入需要判断的年份===
2004
===请输入需要判断的月份===
7
2004年7月有31天!

demo2

DayInMonth.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.Scanner;

public class DayInMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("请输入年份:");
int year = scanner.nextInt();

System.out.println("请输入月份(1-12):");
int month = scanner.nextInt();

if (month == 8 || month == 10 || month == 12) {
System.out.println(month + "月有31天");
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
System.out.println(month + "月有30天");
} else if (month == 2) { // Check for February
if (isLeapYear(year)) {
System.out.println("2月有29天");
} else {
System.out.println("2月有28天");
}
} else if (month == 1 || month == 3 || month == 5 || month == 7) {
System.out.println(month + "月有31天");
} else {
System.out.println("无效的月份");
}

scanner.close();
}

private static boolean isLeapYear(int year) {
return (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0));
}
}

运行结果:

1
2
3
4
5
请输入年份:
2004
请输入月份(1-12):
2
2月有29天
  • Title: Java实战
  • Author: 敬请T期待
  • Created at : 2024-02-07 10:18:12
  • Updated at : 2024-10-30 22:42:52
  • Link: https://kingwempity.github.io/2024/02/07/Java实战/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments