在java里怎么做 从键盘接收4位数字的年份和月份,并判断输出该年该月共有多少天..

任意输入一个四位数,输出该年每一个月的天数,用java 编写2~

试试,不懂追问
public static void main(String args[]){ //建立键盘输入: System.out.println("请输入年份:"); Scanner scanner = new Scanner(System.in); String yearStr = scanner.nextLine(); Calendar cal1 = Calendar.getInstance(); for(int month = 0 ; month<12 ; month ++){ cal1.set(Integer.parseInt(yearStr), month, 1, 0, 0, 0); System.out.println((month+1)+"月天数为:"+cal1.getActualMaximum(Calendar.DAY_OF_MONTH)); } }

用 java编写:输入任意年份和月份,输出对应月份的天数,首先判断输入年份是否是闰年,然后使用switch 方法判断月份,判断代码如下:
public class GetDays {
public static int getDays(int year, int month) {int days = 0;boolean isLeapYear = false;if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {System.out.println("这一年是闰年");isLeapYear = true;} else {System.out.println("这一年不是闰年");isLeapYear = false;}switch (month) {case 1:case 3:case 5:case 7:case 8:case 10:case 12:days = 31;break;case 2:if (isLeapYear) {days = 29;} else {days = 28;}break;case 4:case 6:case 9:case 11:days = 30;break;default:System.out.println("error!!!");break;}return days;}}

扩展资料在java 语言中switch 语法的使用规则为:
1、switch 语句中的变量类型可以是: byte、short、int 或者 char。从 Java SE 7 开始,switch 支持字符串 String 类型了,同时 case 标签必须为字符串常量或字面量。
2、switch 语句可以拥有多个 case 语句。每个 case 后面跟一个要比较的值和冒号。
3、case 语句中的值的数据类型必须与变量的数据类型相同,而且只能是常量或者字面常量。
3、当变量的值与 case 语句的值相等时,那么 case 语句之后的语句开始执行,直到 break 语句出现才会跳出 switch 语句。
参考资料:百度百科—switch

import java.util.Scanner;public class countday { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("请输入年份");
int year = input.nextInt();
System.out.println("请输入月份");
int month = input.nextInt();
boolean bool ;
int num = 0;
if((year%4==0&&year%100!=0)||(year%400==0))
{
bool = true;
}
else
{
bool = false;
}
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
num =31;
break;
case 4:
case 6:
case 9:
case 11:
num = 30;
break;
case 2:
if(bool==true)
{
num=29;
}
else if(bool = false)
{
num =28;
}
break;
}

System.out.println(year+"年"+month+"月有"+num+"天");
}}

相关兴趣推荐

IT评价网,数码产品家用电器电子设备等点评来自于网友使用感受交流,不对其内容作任何保证

联系反馈
Copyright© IT评价网