if语句:
import java.util.*;
public class month {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a year:");
int year = input.nextInt();
String mon = input.next();
if ( (( year % 4==0) && (year % 100 != 0) ||(year % 400==0))&& (mon.equals("Feb")) ) {
System.out.printf("%s %d has 29 days\n",mon,year);
}else if (mon.equals("Jan")){
System.out.printf("%s %d has 31 days",mon,year);
}else if (mon.equals("Feb")){
System.out.printf("%s %d has 28 days",mon,year);
}else if (mon.equals("Mar")){
System.out.printf("%s %d has 31 days",mon,year);
}else if (mon.equals("Apr")){
System.out.printf("%s %d has 30 days",mon,year);
}else if (mon.equals("May")){
System.out.printf("%s %d has 31 days",mon,year);
}else if (mon.equals("Jun")){
System.out.printf("%s %d has 30 days",mon,year);
}else if (mon.equals("Jul")){
System.out.printf("%s %d has 31 days",mon,year);
}else if (mon.equals("Aug")){
System.out.printf("%s %d has 31 days",mon,year);
}else if (mon.equals("Sep")){
System.out.printf("%s %d has 30 days",mon,year);
}else if (mon.equals("Oct")){
System.out.printf("%s %d has 31 days",mon,year);
}else if (mon.equals("Nov")){
System.out.printf("%s %d has 31 days",mon,year);
}else if (mon.equals("Dec")){
System.out.printf("%s %d has 31 days",mon,year);
}else {
System.out.printf("%s is not a correct month name",mon);
}
}
}
运行结果如下:
switch语句:(switch语句要简便很多 有没有)
import java.util.Scanner;
public class month_1 {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a year:");
int year = input.nextInt();
String mon = input.next();
if ( (( year % 4==0) && (year % 100 != 0) ||(year % 400==0))&& (mon.equals("Feb")) ) {
System.out.printf("%s %d has 29 days\n",mon,year);
}else {
switch (mon){
case "Jan":
case "Mar":
case "May":
case "Jul":
case "Aug":
case "Oct":
case "Dec": System.out.printf("%s %d has 31 days",mon,year);
break;
case "Apr":
case "Jun":
case "Sep":
case "Nov":System.out.printf("%s %d has 30 days",mon,year);
break;
case "Feb": System.out.printf("%s %d has 28 days",mon,year);
break;
default:System.out.printf("%s is not a correct month name",mon);
}
}
}
}