# University of Washington, CSE 142 (190)

## Lab 3: Parameters and Graphics

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

lab document created by Whitaker Brand and Marty Stepp

# Today's lab

Goals for today:

• learn the basics of declaring and passing parameters to methods
• practice passing parameters in the context of drawing graphics
• learn to use the instructor-provided `DrawingPanel` class
• learn to use the Java `Graphics` and `Color` classes
• Where you see this icon, you can click it to check the problem in Practice-It!

# Exercise : Parameters

• The following code passes some parameters to a method. What output is produced by the two method calls? Write the output of each call in the box provided.
```public class MysteryNums {
public static void main(String[] args) {
int x = 15;
sentence(x, 42);      // 15 42

int y = x - 7;
sentence(y, x + y);   // 8 23
}

public static void sentence(int num1, int num2) {
System.out.println(num1 + " " + num2);
}
}
```

# Exercise : Parameter Mystery

• Fill in the boxes with the output that each method call would produce:
```public class MysterySoda {
public static void main(String[] args) {
String soda = "coke";
String pop = "pepsi";
String coke = "pop";
String pepsi = "soda";
String say = pop;

carbonated(coke, soda, pop);         // say coke not pepsi or pop
carbonated(pop, pepsi, pepsi);       // say soda not soda or pepsi
carbonated("pop", pop, "koolaid");   // say pepsi not koolaid or pop
carbonated(say, "say", pop);         // say say not pepsi or pepsi
}
public static void carbonated(String coke, String soda, String pop) {
System.out.println("say " + soda + " not " + pop + " or " + coke);
}
}
```

# Exercise : Syntax errors

• The following Java program has 9 errors. Can you find all of them?  ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ``` ```public class Parameters { public static void main() { double bubble = 867.5309; double x = 10.01; printer(double x, double y); printer(x); printer("barack", "obama"); System.out.println("z = " + z); } public static void printer(x, y double) { int z = 5; System.out.println("x = " + double x + " and y = " + y); System.out.println("The value from main is: " + bubble); } } ```
• Copy and paste the code into jGrasp and see if you can fix the errors.

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

# Exercise - Corrected version

• Here is a corrected version of the program:
```public class Parameters {
public static void main(String[] args) {
double bubble = 867.5309;
double x = 10.01;
double y = 5.3;
printer(double x, double y);
printer(x, 0.0);
printer("barack", "obama");
int z = 5;
System.out.println("z = " + z);
}

public static void printer(double x, double y) {
System.out.println("x = " + x + " and y = " + y);
System.out.println("The value from main is: " + bubble);
int z = 5;
}
}
```

# Cumulative algorithms

• A cumulative algorithm is one where you incrementally accumulate a larger value by repeatedly adding, multiplying, etc., and storing the result into a variable over and over.
• Key aspect of a cumulative algorithm: A loop, and a variable declared outside the loop whose value is modified inside the loop.
• Example: Cumulative algorithm to sum the numbers 1-100:
```int sum = 0;
for (int i = 1; i <= 100; i++) {
sum = sum + i;
}
System.out.println(sum);    // 5050
```
• Some of the following problems ask you to write cumulative algorithms.

# Exercise : Powers of 2

• Write a Java method `printPowersOf2` that uses a cumulative algorithm to print out the powers of 2 up to 2x. It should take a parameter that determines x; that is, the exponent of the highest power of 2 to be printed. For example, the following call:
```printPowersOf2(10);
```
should produce the following output, because 210 = 1024:
```1 2 4 8 16 32 64 128 256 512 1024
```
(For this problem it's okay if your numbers have a `.0` at the end of them.)
• Complete the program by writing a `main` method. Call your method several times in `main` to ensure that it works. Also check your answer using Practice-It by clicking the check-mark icon above.

# Exercise : Powers of `n`

• Modify your program from the previous exercise to have a method `printPowersOfN` that prints the powers of any given number n up to n^x. For example, the following call:
```printPowersOfN(3, 5);
```
should produce the following output, because 35 = 243:
```1 3 9 27 81 243
```
and the call:
```printPowersOfN(2, 10);
```
should produce the same output as `printPowersOf2(10);` :
```1 2 4 8 16 32 64 128 256 512 1024
```

# Exercise : Printing `String`s

• Write a method called `printStrings` that accepts a `String` and a number of repetitions as parameters and prints that `String` the given number of times with a space after each time. For example, the call:

```printStrings("abc", 5);
```

will print the following output:

```abc abc abc abc abc
```
• Complete the program with a `main` method. Try calling your method several times from `main` and see what happens when you pass different values.

# Exercise : `printSquare`

We suggest you skip this problem if the lab time is more than half over already.
• Write a method `printSquare` that accepts min and max integers and prints a square of lines of increasing numbers. The first line should start with the minimum; each line that follows should start with the next-higher number. The numbers on a line wrap back to the minimum after it hits the maximum. For example, the call:
```printSquare(3, 6);
```
should produce the following output:
```3456
4563
5634
6345
```
• If the maximum passed is less than the minimum, the method produces no output. Check your answer using Practice-It from the check-mark icon above.

# Graphics

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

• We'll use an instructor-provided class `DrawingPanel` that works with Java classes `Graphics` (a "pen" for drawing shapes) and `Color`.
• Download `DrawingPanel.java` to your program directory.
• For the exercises in this section, you can check your output in the `DrawingPanel` window by clicking File, Compare to Web File....

# Exercise : Syntax errors

• The following program contains 12 mistakes! What are they?  ``` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ``` ```import Java.*; public class PrettyPicture { public static void main(String[] args) { DrawingPanel panel = DrawingPanel(220, 150); setBackgroundColor(Color.YELLOW); Graphics g = panel.Graphics(); panel.setColor(new Color.BLUE); g.drawRectangle(50, 25); g.setColor("RED"); g.fillEllipse(130, 25, 42.1, 40.5); } } ```
• Once you think you've found them all, compile/run your corrected code.

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 11: method name should be `drawRect`
9. line 11: missing two parameters from `drawRect` (width and height)
10. line 12: color should be specified as `Color.RED`, not `"RED"`
11. line 13: method name should be `fillOval`
12. line 13: wrong parameter types; width/height must be integers

# Exercise - corrected version

• Here is a corrected version of the program:
```import java.awt.*;

public class PrettyPicture {
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(220, 150);
panel.setBackground(Color.YELLOW);

Graphics g = panel.getGraphics();
g.setColor(Color.BLUE);

g.drawRect(50, 25, 10, 10);
g.setColor(Color.RED);
g.fillOval(130, 25, 42, 40);
}
}
```

# Exercise : Face

Write a complete Java program that draws the following output:

• window size: 220 x 150 px
• overall face circle: 100 px in diameter; top-left corner at (10, 30)
• eyes: blue circles, 20 px in diameter; top-left at (30, 60) and (70, 60)
• mouth: red line from (40, 100) to (80, 100)

```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 1

Write a complete Java program to draw the following output using a `for` loop to draw the rectangular "stairs." Copy/paste the code template on the next slide into jGRASP as a template to fill in.

• window size: 110 x 110 px
• ten stacked stairs starting at (5, 5), height 10, width starting at 10 and increasing by 10 for each stair

# Exercise - code template

```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++) {
}
}
}
```

```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(5, 5 + 10*i, 10 + 10*i, 10);
}
}
}
```

# Exercise - answer, alternative version

```import java.awt.*;

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

# Exercise : Stairs 2

Modify your previous Java program to draw each of the following outputs. Modify only the body inside your `for` loop.

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);
```

# 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 : Face 2

Modify your previous `Face` program to draw the following output. Write a parameterized method that allows you to draw a face at different positions.

• window size: 320 x 180 px
• faces' top-left corners at (10, 30) and (150, 50)

```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

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

• window size: 520 x 180 px
• faces' top-left at (10, 30), (110, 30), (210, 30), (310, 30), and (410, 30)

```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 : Spiral

Write a Java program that draws the following output using a `for` loop.

• window size: 170 x 170 px
• "spiral" lines starting from (0, 10), going right 160, down 150, left 150, up 140, right 140, down 130, left 130, up 120, ...

```import java.awt.*;

public class Spiral {
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(170, 170);
Graphics g = panel.getGraphics();
for (int i = 0; i < 8; i++) {
g.drawLine(      10*i,   10 + 10*i, 160 - 10*i,  10 + 10*i);  // top
g.drawLine(160 - 10*i,   10 + 10*i, 160 - 10*i, 160 - 10*i);  // right
g.drawLine( 10 + 10*i,  160 - 10*i, 160 - 10*i, 160 - 10*i);  // bottom
g.drawLine( 10 + 10*i,   20 + 10*i,  10 + 10*i, 160 - 10*i);  // left
}
}
}
```

# Exercise - answer, alternative version

```import java.awt.*;

public class Spiral {
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(170, 170);
Graphics g = panel.getGraphics();
int x = 0, y = 10;
int len = 160;
for (int i = 0; i < 8; i++) {
g.drawLine(x, y, x + len, y);  // right
x = x + len;
len = len - 10;
g.drawLine(x, y, x, y + len);  // down
y = y + len;
g.drawLine(x, y, x - len, y);  // left
x = x - len;
len = len - 10;
g.drawLine(x, y, x, y - len);  // up
y = y - len;
}
}
}
```

# Exercise : `printGrid`

We suggest you skip this problem if the lab time is more than half over already.
• Write a method called `printGrid` that accepts two integers representing a number of rows and columns and prints a grid of integers from 1 to (rows*columns) in column-major order.
• For example, the call:
```printGrid(4, 6);
```
should produce the following output:
```1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24
```

# Exercise : Sierpinski Triangle

Write a Java program that draws the following output.... Just kidding!

# 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 Chapter 3 or Supplement 3G and try to solve them! Note that you won't be able to do every problem from Chapter 3; some involve concepts we have not learned yet, such as `return` and `Scanner`.

[an error occurred while processing this directive]