University of Washington, CSE 142

Lab 2: For loops, Parameters, Graphics

Except where otherwise noted, the contents of this document are Copyright 2012 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges and Whitaker Brand

Basic lab instructions

Today's lab

Goals for today:

Exercise : printing a design practice-it

Write a program to produce the following output using nested for loops. Use a table to help you figure out the patterns of characters on each line.

-----1-----
----333----
---55555---
--7777777--
-999999999-
Line Dashes Numbers
1
5
1
2
4
3
3
3
5
4
2
7
5
1
9
dashes expression
-1
* line +
6
numbers expression
2
* line +
-1

Test your loop expressions in Practice-It! using the checkmark icon above. Use your expressions in the loop tests of the inner loops of your code.

Exercise : SlashFigure practice-it

Write a Java program in a class named SlashFigure to produce the following output with nested for loops. Use a loop table if necessary to figure out the expressions.

!!!!!!!!!!!!!!!!!!!!!!
\\!!!!!!!!!!!!!!!!!!//
\\\\!!!!!!!!!!!!!!////
\\\\\\!!!!!!!!!!//////
\\\\\\\\!!!!!!////////
\\\\\\\\\\!!//////////
Line \ ! /
1
0
22
0
2
2
18
2
3
4
14
4
4
6
10
6
5
8
6
8
6
10
2
10
multiplier
2
-4
2
shift
-2
26
-2

Test your code in Practice-It! or the Output Comparison Tool.

Class constants

A class constant is a global value that cannot be changed.

public static final type name = expression;

Example:

public static final int DAYS_PER_WEEK = 7;
public static final double TAX_RATE = 0.10;

for loop expressions w/ constant

When adding a class constant to a loop expression, it affects the constant that must be added in the expression. Suppose we have the two loop expressions below for figure sizes of 5 and 9. The third line of the table shows the general formula that would be used if we turned our figure's size into a constant named SIZE.

size expression relationship
5 8 * line + 16 16 = 3 * 5 + 1
9 8 * line + 28 28 = 3 * 9 + 1
SIZE 8 * line + (3 * SIZE + 1)

continued on the next slide ...

Exercise : for loop table w/ constant

You already found loop expressions for the slash figure at size 6. Now make a table at size 4 and use the two to generalize the loop expression in terms of a constant for the figure size.

!!!!!!!!!!!!!!
\\!!!!!!!!!!//
\\\\!!!!!!////
\\\\\\!!//////
Line \ ! /
1
0
14
0
2
2
10
2
3
4
6
4
4
6
2
6
\ and /
size 6  2 * line +
-2
size 4  2 * line +
-2
size SIZE  2 * line +
-2
!
size 6 -4 * line +
26
size 4 -4 * line +
18
size SIZE -4 * line + (
4
 * SIZE +
2
)

Exercise : SlashFigure2

Test your code in the Output Comparison Tool.

Exercise : jGRASP Debugger

continued on the next slide...

Exercise - jGRASP Debugger

continued on the next slide...

Exercise - jGRASP Debugger

Variable Scope

A variable's scope is the part of a program in which it exists. In Java, the scope of a variable starts when it is declared and ends when the closing curly brace for the block that contains it is reached. A variable is said to be in scope where it is accessible.

public class Example {
    public static void main(String[] args) {
        performTest();
    }
	
    public static void performTest() {
        int count = 12;
        for (int i = 1; i <= 12; i++) {
            runSample();
            System.out.print(count);   
        }
    }

    public static void runSample() {
	    System.out.print("sample");
    }
} 
In which of these two blocks is the variable count in scope?

Parameters

A parameter allows you to pass in a value to a method as you call it.

public static void name(type name) {   // declare
methodName(expression);                // call

Example:

public static void squared(int num) {
    System.out.println(num + " times " + num + " is " + (num * num));
}
...
squared(3);          // 3 times 3 is 9
squared(8);          // 8 times 8 is 64

Exercise : Parameters output

Solving "Parameter Mystery" problems

Exercise : Parameter Mystery practice-it

Exercise : Parameter Mystery practice-it

Exercise : Parameter Mystery practice-it

Exercise : Syntax errors

Exercise - answer

  1. line 5: cannot use variable y without declaring and initializing it
  2. line 5: cannot declare the type of y in the method call
  3. line 6: cannot call printer without the correct number of parameters (2, in this case)
  4. line 7: cannot call printer by passing the correct type of parameters (double, in this case)
  5. line 8: cannot refer to the variable z: it is in scope inside printer, not main
  6. line 11: must provide a type for x
  7. line 11: must provide a variable name for the second parameter
  8. line 12: must refer to the parameters using the exact same spelling
  9. line 13: cannot refer to variables in main that were not passed into printer as a parameter

Exercise - Corrected version

Graphics

Now we'll explore several exercises related to drawing graphics.

quilt drawingpanel compare

Parameterized methods and Graphics

When you want to divide a graphical program into multiple drawing methods, you must pass Graphics g as a parameter in addition to any other parameters. Example:

public static void main(String[] args) {
    DrawingPanel panel = new DrawingPanel(400, 300);
    Graphics g = panel.getGraphics();
    ...
    drawStuff(g, 13, 52, 7);
}

public static void drawStuff(Graphics g, int a, int b, int c) {
    g.drawLine(a, 45, b, c);
    ...
}

Exercise : Syntax errors

answer on next slide...

Exercise - answer

  1. line 1: incorrect import statement; should import java.awt.*
  2. line 5: missing word new before 2nd occurrence of DrawingPanel
  3. line 6: method name should be setBackground
  4. line 6: missing panel. before setBackground
  5. line 8: method name should be getGraphics
  6. line 9: the setColor method is part of object g, not panel
  7. line 9: should not write new before Color.BLUE
  8. line 10: method name should be drawRect
  9. line 10: missing two parameters from drawRect (width and height)
  10. line 11: color should be specified as Color.RED, not "RED"
  11. line 12: method name should be fillOval
  12. line 12: wrong parameter types; width/height must be integers

Exercise - corrected version

Exercise : Face practice-it

Write a complete Java program that draws the following output:

face

Exercise - answer

import java.awt.*;

public class Face1 {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(220, 150);
        Graphics g = panel.getGraphics();
        
        g.drawOval(10, 30, 100, 100);   // face outline
        g.setColor(Color.BLUE);
        g.fillOval(30, 60, 20, 20);     // eyes
        g.fillOval(70, 60, 20, 20);
        g.setColor(Color.RED);          // mouth
        g.drawLine(40, 100, 80, 100);
    }
}

Exercise : Stairs loop table

stairs 1

Consider the output at right. The first stair's top-left corner is at position (5, 5). The first stair is 10x10 px in size. Each stair is 10px wider than the one above it.

Fill in the table below with the coordinates and sizes of the first five stairs. Note which values change and which ones stay the same.

stair x y width height
1
5
5
10
10
2
5
15
20
10
3
5
25
30
10
4
5
35
40
10
5
5
45
50
10

Exercise : Stairs practice-it

stairs 1

Write a complete Java program to draw the stairs. Copy/paste the code template below into jGRASP and fill in your own expressions or values for each stair's x, y, width, and height.

Use your table from the previous slide to help you find the correct expressions. The values that change for each stair should become expressions in terms of the loop counter variable, i.

import java.awt.*;

public class Stairs1 {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(110, 110);
        Graphics g = panel.getGraphics();
        for (int i = 0; i < 10; i++) {
            g.drawRect(x, y, width, height);
        }
    }
}

Exercise : Stairs 2 practice-it

Modify your stairs program to draw one (or all) of the following outputs. Modify only the body in your for loop. (You may want to make a new table to find the expressions for x, y, width, and height.)

stairs 1stairs 2 stairs 3 stairs 4

Exercise - answer

To get each output, change the for loop body to the following:

// output 2
g.drawRect(5, 5 + 10*i, 100 - 10*i, 10);
// output 3
g.drawRect(95 - 10*i, 5 + 10*i, 10 + 10*i, 10);
// output 4
g.drawRect(5 + 10*i, 5 + 10*i, 100 - 10*i, 10);

Exercise : Face 1+2

face

Suppose you have an existing program that draws the "face" figure at right. Let's modify the program using methods and parameters so that we can draw several faces at different locations.

continued on the next slide...

Exercise : Face 2 practice-it

Modify the Face program to draw the following output. Write a parameterized method that draws a face at different positions.

face 2

Exercise - answer

import java.awt.*;

public class Face2 {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(320, 180);
        Graphics g = panel.getGraphics();
        drawFace(g, 10, 30);
        drawFace(g, 150, 50);
    }
    
    public static void drawFace(Graphics g, int x, int y) {
        g.setColor(Color.BLACK);
        g.drawOval(x, y, 100, 100);
        g.setColor(Color.BLUE);
        g.fillOval(x + 20, y + 30, 20, 20);
        g.fillOval(x + 60, y + 30, 20, 20);
        g.setColor(Color.RED);
        g.drawLine(x + 30, y + 70, x + 70, y + 70);
    }
}

Exercise : Face 3 practice-it

Modify your previous Java program to draw the following output. Use a for loop with your parameterized method to draw faces at different positions.

face 2

Exercise - answer

import java.awt.*;

public class Face3 {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(520, 180);
        Graphics g = panel.getGraphics();
        for (int i = 0; i < 5; i++) {
            drawFace(g, 10 + i * 100, 30);
        }
    }
    
    public static void drawFace(Graphics g, int x, int y) {
        g.setColor(Color.BLACK);
        g.drawOval(x, y, 100, 100);
        g.setColor(Color.BLUE);
        g.fillOval(x + 20, y + 30, 20, 20);
        g.fillOval(x + 60, y + 30, 20, 20);
        g.setColor(Color.RED);
        g.drawLine(x + 30, y + 70, x + 70, y + 70);
    }
}

Exercise : Number lines, part 1 practice-it

Exercise : Number lines, part 2 practice-it

Exercise : Number lines, part 3 practice-it

Exercise : printGrid practice-it

Exercise : printSquare practice-it

If you finish them all...

If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.

You can view an exercise, type a solution, and submit it to see if you have solved it correctly.

Choose some problems from the book and try to solve them!