Programming 1, fall 2007 -- Demonstration 8

We have now seen most of the fundamentals. The rest of the course is about:

The rest of your programming career is about:

Postponed from last time:

Further data structures: multidimensional arrays

Continue from last time's object exercises, if you haven't done them yet.

Exercise 1: double[][] - a "matrix"

Implement a subroutine that creates and returns a new matrix of double values, with random values. The parameters should include the number of rows and columns in the matrix, and the lower and upper limit of the random values. You get a random value between 0.0 and 1.0 by calling Math.random() -- then you need to make a mathematical transformation to map the random number into the desired range.

Implement another subroutine for printing out the values... to see that your random generator works as you expect.

Ask for help on the mailing list, if you run into problems!

Further control structures

Exercise 2: Switch

Make a subroutine that returns the day-of-week as a string, based on an integer input (range 1-7). Example:

System.out.println(dayOfWeekAsString(2)); // expect "Tuesday"
System.out.println(dayOfWeekAsString(6)); // expect "Saturday"
System.out.println(dayOfWeekAsString(-2)); // expect "UNSPECIFIED"

Use the switch-statement.

Exercise 3: A shorter version

Implement the dayOfWeekAsString() from exercise 2 by pre-defining an array of Strings with contents "Monday", "Tuesday" etc. Then just return a string reference from the table, instead of making a switch.

You need to understand switch, but also that for some problems, there are more elegant solutions (that also perform faster in a computer). For some problems, switch is the better solution. It all depends on what is to be done...