Skip to main content
ICT
Lesson A12 - Iterations
 
Main   Previous Next
 

LAB ASSIGNMENT A12.6 page 17 of 18

ParallelLines

Background:

In this lab, you will practice using nested for loops to recreate the image shown below:

To do this efficiently, there are a few suggestions to consider. First, there are eight rows each containing seven filled boxes. This suggests a nested for loop, like this:

for ( int row = 0; row < 8; row++ )
{
  // calculate the start of the row of squares

  // calculate and add a horizontal offset

  for ( int col = 0; col < 7; col++ )
  {
    // draw the square
    // calculate and position for the next square
  }

  // calculate the location and draw the line
}

Calculating the square position will take some work. You might want to (or SHOULD...) make a quick sketch, with coordinates, to make it easier to visualize.

The statement

g.drawLine(x1, y1, x2, y2);

draws a line from point (x1, y1) to point (x2, y2) and can be used to create the parallel line segments.

The statement

g.fillRect(x, y, width, height)

draws a filled rectangle with the top left corner at the coordinate (x, y) and with width width and height height. In other words, the left and right edges of the rectangle are at x and x + width - 1. The top and bottom edges are at y and y + height - 1. The rectangle is filled using the graphics context's current color. This method can be used to create the filled rectangles displayed on each row.

Hint: Try drawing short lines to experiment with the coordinates. Do you know where (0,0) is? Draw a line from (0,0) to (10,20) (i.e. g.drawLine(0, 0, 10, 20)). Do you know the coordinates of the other corners of the window? Try writing code to draw some small boxes or some small lines at different places before you even try to draw the more complicated parallel line image.

Assignment:

  1. Using the information given in the section above, edit the ParallelLines class using nested for loops to display the image shown above.

  2. Hint: Work on a piece at a time. Draw one line. Then draw 8 lines. Draw one box of the row. Then draw 7 boxes of a single row. Draw 8 rows of 7 boxes. Then create the final illusion where you offset the starting point of each row.

  3. When you are finished, submit your program to Web-CAT. Then take a screenshot of your output and name it period_lastName_firstName_plines.jpg (with your name of course...). Once have you done so, submit your image to the assignment in Schoology.

 

Main   Previous Next
Contact
 © ICT 2006, All Rights Reserved.