方法一:控制台输入月份
package com.liaojianya.chapter1;
import java.util.Scanner;
/**
* This program demonstrates thw way of implements
* display the number of days according to 12 months.
* @author Hugh
* 2016年7月19日
*/
public class MonthAndDays
{
public static void main(String[] args)
{
System.out.println("please enter a number : 1~12");
@SuppressWarnings("resource")
Scanner scan = new Scanner(System.in);
int month = scan.nextInt();
switch (month)
{
case 1:
System.out.println("January has 31 days");
break;
case 2:
System.out.println("February has 28 days");
break;
case 3:
System.out.println("March has 31 days");
break;
case 4:
System.out.println("April has 30 days");
break;
case 5:
System.out.println("May has 31 days");
break;
case 6:
System.out.println("June has 30 days");
break;
case 7:
System.out.println("July has 31 days");
break;
case 8:
System.out.println("August has 31 days");
break;
case 9:
System.out.println("September has 30 days");
break;
case 10:
System.out.println("Octor has 31 days");
break;
case 11:
System.out.println("November has 30 days");
break;
case 12:
System.out.println("December has 31 days");
break;
default:
System.out.println("Error month information");
}
}
}
运行结果:
please enter a number : 1~12
4
April has 30 days
方法二:随机产生1-12之间的某个整数:
package com.liaojianya.chapter1;
/**
* This program demonstrates thw way of implements
* display the number of days according to 12 months.
* @author Hugh
* 2016年7月19日
*/
public class MonthAndDays
{
public static void main(String[] args)
{
int month = (int)(Math.random() * 12);
System.out.println("随机产生一个月份并显示月份: " + month);
switch (month)
{
case 1:
System.out.println("January has 31 days");
break;
case 2:
System.out.println("February has 28 days");
break;
case 3:
System.out.println("March has 31 days");
break;
case 4:
System.out.println("April has 30 days");
break;
case 5:
System.out.println("May has 31 days");
break;
case 6:
System.out.println("June has 30 days");
break;
case 7:
System.out.println("July has 31 days");
break;
case 8:
System.out.println("August has 31 days");
break;
case 9:
System.out.println("September has 30 days");
break;
case 10:
System.out.println("Octor has 31 days");
break;
case 11:
System.out.println("November has 30 days");
break;
case 12:
System.out.println("December has 31 days");
break;
// default:
// System.out.println("Error month information");
}
}
}
运行结果:
随机产生一个月份并显示月份: 3
March has 31 days
分析:随机产生月份时,default可以省略。
显示12个月各自全部的天数:
package com.liaojianya.chapter1;
/**
* This program demonstrates the way of using array to storage days of each month.
* @author Hugh
* 2016年7月19日
*/
public class ArrayDemo
{
public static void main(String[] args)
{
int[] month = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
for(int i = 0; i < month.length; i++)
{
System.out.println("第" + (i+1) + "月有" + month[i] + "天!");
}
}
}
运行结果:
第1月有31天!
第2月有28天!
第3月有31天!
第4月有30天!
第5月有31天!
第6月有30天!
第7月有31天!
第8月有31天!
第9月有30天!
第10月有31天!
第11月有30天!
第12月有31天!