Methods
[Framework practical 3 of 7]


Ok, so now we'll build the other three methods.


 

Have a go at writing the printArray method in Storage.

Remember, if you merged together any of the code last practical (for example, doing the values printing within the loop working out the maximum and/or minimum) you'll need to separate out the code into separate loops before splitting off the printing code and putting it in the Storage class as a method.

The call from the Analyst class will look like this:

store.printArray();


Once you've had a go at writing the printArray method, remove your code in Analyst from the last practical that printed the array, compile the code and check it runs.


If you managed that, you should now be able to write the getMaximum and getMinimum methods. The only difference with these two methods is that they should return double values to wherever they are called from. This means that you'll need to declare a return type other than void in their declarations, and you'll need to call the methods from Analyst like this:

double max = store.getMaximum();

You'll also need to end each method, after all the loops are finished, with a return statement returning the answer. Look at the lecture materials again if you are unsure how to do this.

Write the two methods, one at a time, in the Storage class, and make sure you test each by calling it from Analyst and printing the result with a standard System.out.println, having first removed the code to find the maximum and minimum from the Analyst class.


What you should end up with is an Analyst class that has this kind of algorithm, each line being replaced by one line of code:

// Make the Storage object called 'store'.
// Randomise the values.
// Check the data is randomised using printArray.
// Get the maximum.
// Print the maximum.
// Get the minimum.
// Print the minimum.

You can take out everything else (leaving the main and constructor code, obviously).

Compare this with last practical's code and you should find it much easier to understand Analyst at a quick glance. This is what all main class constructors should ideally look like: something that gives you a quick overview of what is going on with your program, delegating the work to other classes and/or methods.


Once you have all four methods working, you're done for this practical. If you want some extra coding practice, write set and get methods for the data array and positions within the data array. You could the set and get methods by passing in and getting back a new 2D double array, created in Analyst thus:

double[][] newArray = {{1.0,2.0,3.0},{4.0,5.0,6.0},{7.0,8.0,9.0},{10.0,11.0,12.0}};

Remember, when passing in an array, you use the array name ("newArray"), rather than a position within the array ("newArray[1][2]").