java接收用户输入的年份year和月份month,计算该年该月的天数,并输出
时间: 2023-05-13 13:06:51 浏览: 90
可以使用Java中的Calendar类来计算该年该月的天数,代码如下:
```java
import java.util.Calendar;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
System.out.print("请输入月份:");
int month = scanner.nextInt();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(year + "年" + month + "月有" + days + "天");
}
}
```
输入年份和月份后,程序会输出该年该月的天数。
相关问题
java接收用户输入的年份year和月份month,计算该年该月的天数,并输出。不使用C alendar
可以使用以下代码实现:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
System.out.print("请输入月份:");
int month = scanner.nextInt();
int days = 0;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
break;
default:
System.out.println("输入的月份不正确!");
return;
}
System.out.println(year + "年" + month + "月有" + days + "天。");
}
}
这段代码使用了 switch 语句来根据月份计算天数,其中对于闰年的判断使用了 if 语句。
java接收用户输入的年份year和月份month,计算该年该月的天数,并输出。不使用Calendar类和 switch
语句,可以使用if语句或者循环语句。
以下是代码示例:
```
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入年份:");
int year = scanner.nextInt();
System.out.print("请输入月份:");
int month = scanner.nextInt();
int days = 0;
if (month == 2) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
days = 30;
} else {
days = 31;
}
System.out.println(year + "年" + month + "月有" + days + "天。");
}
}
```
这段代码使用了if语句来判断月份和年份,从而计算出该月的天数。如果是闰年的二月份,天数为29天,否则为28天;如果是4月、6月、9月或11月,天数为30天;其它月份天数为31天。最后输出结果。
希望这个回答能够帮助到你。