RU beehive logo ITEC dept promo banner
ITEC 120
2009spring
ibarland
nokie
jmdymacek

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs

lab12b
cleaning up main

The previous lab had three phases: read input, print the average, and then have a user repeatedly probe the array interactively.

Today's task: rewrite your program so that main is only three lines long (but it still behaves as before):

    public static void main( String[] args ) {
        double[] myNums = readArrayFromKbd(5);
        System.out.println( "The average value is " + avg(myNums) );
        letUserQueryArray(myNums);
    }
Of course, you'll need to package the code from last week into separate methods, which are being called from main! You'll need to think about what information needs to be passed to each of the two new helper methods.

(Make those methods static, since their answer doesn't depend on which object is being called.)

Discussion: is this code easier to write and understand, or more difficult? Is writing the helper methods easier, when they are only in charge of one small task, independent of the rest of program?
In general, humans can only cope with large software systems by breaking them down into small, independent methods (and classes) which call each other. Large programs will have literally thousands of methods. (And often, each individual method will be quite short.)


Reading input

Note: We have relaxed lab12a's problem statement, so that we can assume the user only types integers, and never a non-integer; we stop when we read a number not in the expected range.

Here is a high-level description of how to handle the input-gathering, when we can assume that only integers are entered:

  n ← prompt-and-read-a-number
  while n is in 1..5, begin:
    print the requested item from our array
    n ← prompt-and-read-a-number
  endwhile
(Of course, this is written in pseudocode, not actual Java.) The steps for "prompt-and-read-a-number" might be a couple lines of code, and has to be repeated in two places (ugh) — a “loop and a half”.

For the curious, If you really wanted to handle the case which includes non-integers being typed:

homeinfolectslabsexamshws
textbooktutor/PIsjava.lang docsjava.util docs


©2009, Ian Barland, Radford University
Last modified 2009.Apr.15 (Wed)
Please mail any suggestions
(incl. typos, broken links)
to iba�rlandrad�ford.edu
Powered by PLT Scheme