Arrays

The next example uses an array to store the number of days in each month. The user can enter the number of a month and find out how many days are in the month. The array is declare to have 13 elements. They will be number 0 to 12. We won't be using element 0, but it is easier to understand if January is element 1 and December is element 12.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Months: print name of month and number of days.
package calendar;
import java.util.*;
public class DaysinMonth {
  public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in); 
    int[] days={0,31,28,31,30,31,30,31,31,30,31,30,31};
    String[] month={"","January", "February","March", "April",
        "May","June","July","August","September","October",
        "November", "December"};
    System.out.print("Enter the number of a month:");
    int mth=keyboard.nextInt();
    if (mth<1 || mth>12) System.out.println(mth+" is not a valid month");
    else System.out.println(month[mth]+" has "+days[mth]+" days.");
  }//main
}//class
CODE

Explanation:

  • An array can be given initial values. Something must be put in days[0] in order for the other numbers to be in the right place.
  • Not everything is an array! Sometimes students learn about arrays and start making everything an array.
  • It is the programmers responsibility to make sure that no attempt is made to use a subscript that is out of bounds.

NEXT: