Next: Method naming
Up: 6 Multiple methods
Previous: Passing information between methods
Contents
A method can not alter the values of any of its arguments.
Thus the following is not valid code and will not compile.
public static int increment(int i)
{
i += 3; // this is not allowed, code will not compile
return i;
}
You do not have to restrict yourself to calling additional methods
just from the main method. If you have two or more additional
methods one may call another.
Exercise 6.2
(9 marks)
Starting with the class MultMethEx1 you wrote for the previous
exercise, make a new version of the class called MultMethEx2.
- (i)
- Add a new method called calcTriangleArea that
performs the same calculation as printTriangleArea did, but
instead of printing the area to the screen, it returns the area as a
double. Modify main to use both methods and show that
they produce the same result.
- (ii)
- Change the code in the method printTriangleArea so
that it uses the new method calcTriangleArea instead of
calculating the area itself. No changes to main should be
necessary. Demonstrate that your program produces the same result.
- (iii)
- Add a method testIfValidTriangle which takes the
three sides as arguments and checks that they form a valid triangle,
according to the criteria given in the previous exercise. This
method should return a boolean value: true if the sides do
make a valid triangle, or false if not. Use the
testIfValidTriangle method in the main
method to validate the input before trying to calculate the
area.
Note that in answering question (ii) you have benefited from having
encapsulated a well-defined part of your program inside a
separate method (printTriangleArea). This allows you to
modify the internal workings of this method without requiring
any changes elsewhere in the program where the method is
used.
Include the program listings and sample outputs from all the questions
above in your lab book.
Next: Method naming
Up: 6 Multiple methods
Previous: Passing information between methods
Contents
RHUL Dept. of Physics