Introduction to Programming (CPSC 124)
—Hobart & William Smith Colleges, Fall 2014
Thursday Lab #5
Home | Syllabus | Calendar | Class Notes | Labs and Projects | General Notes

Due by 2:59 pm on Friday, 10/03/2014)

# Arrays: A Few Examples

Run each of the following programs, several times each, varying your choice of inputs in a way that exercises the different behaviors. First, an example that uses arrays as lookup tables (in this case, month names and maximum day values). There are also two example of the "literal creation" form.

```
public class DateFormat {
public static void main(String[] args) {

int y = Integer.parseInt(args[0]);
int m = Integer.parseInt(args[1]);
int d = Integer.parseInt(args[2]);

// First, we'll validate the date itself:

int[] maxDays = new int[]{31,28,31,30,31,30,31,31,30,31,30,31};
boolean leapYear = (y %4 == 0) && (y % 100 != 0 || y %400 == 0);
if (leapYear) {
maxDays[1] = 29;
}

boolean valid = (1 <= m && m <= 12);    // valid month?
valid = valid && (1 <= d);              // Is d >= 1 ?
valid = valid && (d <= maxDays[m-1]);   // Is d no bigger than the max?

if (!valid) {
System.out.println("Sorry.  Invalid Date");
} else {
// Now we'll print the formatted date (which we know is valid)

String[] monthNames = new String[]{"January", "February", "March",
"April", "May", "June", "July",
"August", "September",
"October", "November",
"December"};

System.out.println(monthNames[m-1]+ " " + d + ", " + y);
}
} // end of main()
} // end of class DateFormat

```

Pay special attention to the declaration and usage of the variables maxDays and monthNames. Both of these variables have an array type, the first an array of int values, the second an array of String.

Here's another one, similar to last week's lab problem of finding an average, but this time, we're going to calculate the median of a bunch of numbers (the median is the value that divides the set in half—half of the other numbers are below the median, and half are equal to or greater than it). Like the "average" problem, we'll make this one interactive, rather than read values from the command line. One significant difference from that problem is that we need to know in advance how many numbers to read:

```
import java.util.Scanner;

public class Median {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);

System.out.print("How many values?");
int sz = inp.nextInt();  // we'll ignore error handling here

double[] nums = new double[sz];

System.out.print("Numbers (letter to quit):  ");
int i = 0;
while (i < nums.length) {
nums[i] = inp.nextDouble();
i = i + 1;
}

//  Now we have an array containing all the values entered.  We just
//  need to sort them and pick the middle value.

//  Luckily, there's a built-in method for sorting!
java.util.Arrays.sort(nums);

int mid = nums.length/2;

System.out.println(nums[mid]);
} // end of main()
} // end of class Median

```

These two examples illustrate everything we can do with an array:

• Declaration of array-type variables:

```        < element type >  []
```

Examples above are "int[] maxDays", "String[] monthNames", and "double[] nums".

• Initialization of an array value (literal form):

```        new< element type >  []{ < list of values >}
```

Examples above are

```        new int[]{31,28,31,30,31,30,31,31,30,31,30,31}

new String[]{"January", "February", "March", "April", "May", "June",
"July",  "August", "September", "October", "November",
"December"}
```
• Initialization of an array value (general form):

```        new< element type >  [ < number of elements >]
```

The one example of this above is "new double[sz]".

• Getting the number of elements in an array:

```        < element type > .length
```

That's used above in the while test—"while(i < nums.length)". You've also seen it whenever you've used args.length!

• Reading from/writing to an array element:

```        < array > [ < index number > ]
```

There are many examples of this above:

```        maxDays[1] = 29;
valid = valid && (d <= maxDays[m-1]);
System.out.println(monthNames[m-1]+ " " + d + ", " + y);
nums[i] = inp.nextDouble();
System.out.println(nums[mid]);
```

1. Modify the DateFormat program so that it handles bad input (i.e. too few arguments or non-integer arguments) using exception handling.

2. Modify the Median program so that there is a second loop, after the numbers are read but before they are sorted. This loop should print out every number in the array, with a "," separating each value.

For a truly satisfying version, write this "print out" code so that there are only commas separating the values: no trailing comma at the end.

# Turn In

• A printed copy of your two programs.

• An electronic copy of your work should be copied to your class turn-in folder, inside of a folder named lab5.

John H. E. Lasseter