COP 2250Laboratory 5:forLoops, Methods, Parameters
Download the exerciseprogram-stubs to a folder 2250Lab5 on your flash drive.
Exercise 1 (for-loops):
Compile and run Lab5_ForLoop.java. It prints a Line of width 12 by printing 12 *’s. Then it prints a 5x12 Rectangle by printing 5 lines of width 12. The program uses while-loops.
When using a counting while-loop, there are always 3 phases:
- Initialization: a counter is initialized to some starting value
- Termination: the counter’s value is compared against some final value
- Updating: the counter’s current value is updated (usually incremented)
A counting while-loop can be rewritten as a for-loop by bringing the 3 phases into a single-line control structure: for (Initialization; Termination; Updating)
In the code to draw a Line, the 3 phases are marked by comments. Re-write this code to use a for-loop instead of a while-loop. Make sure that it compiles and runs.
The code to draw a Rectangle uses 2 while-loops, one nested inside the other. Replace both while-loops with suitable for-loops. Re-compile and run again.
Exercise 2 (simple methods):
Compile and run Lab5_ForLoop.java. Just as the previous exercise, the program prints a Line of width 12 and a 5x12 Rectangle. This program uses a separate method for each of the two tasks: drawLine() and drawRectangle(). Each method
- Has a definition that begins private static void and the method-name followed by a block that contains the statements to implement the method.
- Is called by the main() method by writing the method-name() as a statement.
Note: The constants are now defined at the class level to make them available to all of the methods of the class, not just main().
An advantage of using methods is that a program can call the same method as often as needed to repeat the same task; this is much better than having to write identical code several times. Drawing a Rectangle requires drawing a Line many times.
Modify thedrawRectangle() method definition to call the drawLine() method.
Exercise 3 (parameters):
Compile and run Lab5_Parameters.java. As in the previous exercise, the program prints a Line of width 12 and a 5x12 Rectangle, but the method definitions now both include a parameter for the width of the Line or Rectangle.
Change the method calls in main() to make the program draw a Line of width 10, and a Rectangle of width 15. Repeat for varying widths!
Modify the definition of the drawRectangle() method so that it can draw a Rectangle of any size. Hint: You need a parameter for the height of the Rectangle.You must change the method call in main() to initialize the new parameter!
Implement the drawTriangle() method using drawLine() calls. Hint: This is almost the same as the drawRectangle() method, but with a small, but subtle, difference.
Parameterize the drawing symbol in all of your methods.