[an error occurred while processing this directive] CSE 142 Lab 3: Parameters, Graphics

University of Washington, CSE 142

Lab 3: Parameters, Graphics

Except where otherwise noted, the contents of this document are Copyright 2013 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:

Parameters

A parameter allows you to pass in a value (an expression or a variable!) to a method as you call it.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public static void main(String[] args) {
   squared(3);          // 3 times 3 is 9
   squared(8);          // 8 times 8 is 64  
   
   int x = 5;
   squared(x);          // 5 times 5 is 25

   squared(2 + 2)       // 4 times 4 is 16
}

public static void squared(int num) {
    System.out.println(num + " times " + num + " is " + (num * num));
}
[an error occurred while processing this directive]

Graphics

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

quilt drawingpanel compare
[an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive] [an error occurred while processing this directive]

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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);
    ...
}
[an error occurred while processing this directive] [an error occurred while processing this directive]

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!