Except where otherwise noted, the contents of this document are Copyright 2011 Stuart Reges and Marty Stepp.
lab document created by Marty Stepp, Stuart Reges, and Whitaker Brand
Goals for today:
DrawingPanel
and Java's Graphics
and Color
classesreturn
values to send data between methodsif/else
statements to select between multiple code actionsScanner
to create interactive programs that read user inputclass mean for a1 (i.e., average score for assignment 1) | / 10 |
8.90 |
class mean for lab1 (i.e., average score for lab 1) | / 2 |
1.92 |
Now we'll explore several exercises related to drawing graphics.
DrawingPanel
that works with Java classes Graphics
(a "pen" for drawing) and Color
.
DrawingPanel.java
to your program directory.
DrawingPanel
, click File, Compare to URL....
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 |
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); } } }
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.)
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);
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); ... }
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...
Modify the Face
program to draw the following output.
Write a parameterized method that draws a face at different positions.
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); } }
Modify your previous Java program to draw the following output.
Use a for
loop with your parameterized method to draw faces at different positions.
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); } }
A return value is when a method sends a value back to the code that called it.
public static type name(parameters) { // declare
...
return expression;
}
variableName = methodName(parameters); // call
Example:
public static double fToC(double tempF) { return (tempF - 32) * 5.0 / 9.0; } ... double bodyTemp = fToC(98.6); // bodyTemp stores 37.0 double freezing = fToC(32); // freezing stores 0.0
Method | Description | Example |
---|---|---|
Math.abs
|
absolute value |
Math.abs(-308) returns 308
|
Math.ceil
|
ceiling (rounds upward) |
Math.ceil(2.13) returns 3.0
|
Math.floor
|
floor (rounds downward) |
Math.floor(2.93) returns 2.0
|
Math.max
|
max of two values |
Math.max(45, 207) returns 207
|
Math.min
|
min of two values |
Math.min(3.8, 2.75) returns 2.75
|
Math.pow
|
power |
Math.pow(3, 4) returns 81.0
|
Math.round
|
round to nearest integer |
Math.round(2.718) returns 3
|
Math.sqrt
|
square root |
Math.sqrt(81) returns 9.0
|
Write the results of each expression.
Use the proper type (such as .0
for a double
).
Note that a variable's value changes only if you re-assign it using the =
operator.
double grade = 2.7; Math.round(grade); // grade = 2.7 grade = Math.round(grade); // grade = 3.0 double min = Math.min(grade, Math.floor(2.9)); // min = 2.0 double x = Math.pow(2, 4); // x = 16.0 x = Math.sqrt(64); // x = 8.0 int count = 25; Math.sqrt(count); // count = 25 count = (int) Math.sqrt(count); // count = 5 int a = Math.abs(Math.min(-1, -3)); // a = 3
Consider the following method for converting milliseconds into days:
// converts milliseconds to days public static double toDays(double millis) { return millis / 1000.0 / 60.0 / 60.0 / 24.0; }
Write a similar method named area
that takes as a parameter the radius of a circle and that returns the area of the circle.
For example, the call area(2.0)
should return 12.566370614359172
.
Recall that area can be computed as π times the radius squared and that Java has a constant called Math.PI
.
Write a method named pay
that accepts two parameters: a real number for a TA's salary, and an integer for the number of hours the TA worked this week.
The method should return how much money to pay the TA.
For example, the call pay(5.50, 6)
should return 33.0
.
The TA should receive "overtime" pay of 1 ½ normal salary for any hours above 8.
For example, the call pay(4.00, 11)
should return (4.00 * 8) + (6.00 * 3) or 50.0
.
if/else
StatementsAn if/else statement lets your program choose between 2 or more options.
if (test) { statement(s); } else { statement(s); }
Example:
if (gpa >= 2.0) { System.out.println("Welcome to Mars University!"); } else { System.out.println("Please apply again soon."); }
if
/else
mysteryConsider the following Java code. Fill in the boxes with the output produced by each of the method calls.
public static void mystery(int n) { System.out.print(n + " "); if (n > 10) { n = n / 2; } else { n = n + 7; } if (n * 2 < 25) { n = n + 10; } System.out.println(n); } |
|
Write a method named numUnique
that accepts three integers as
parameters and that returns the number of unique integers among the three.
For example, the call numUnique(18, 3, 4)
should return 3
because the parameters have 3 different values. By contrast, the
call numUnique(6, 7, 6)
would return 2 because there are only
2 unique numbers among the three parameters: 6 and 7.
Scanner
Method name | Description |
---|---|
nextInt()
|
reads and returns the next token as an int , if possible
|
nextDouble()
|
reads and returns the next token as double , if possible
|
next()
|
reads and returns a single word as a String
|
nextLine()
|
reads and returns an entire line as a String
|
Example:
import java.util.*; // so you can use Scanner ... Scanner console = new Scanner(System.in); System.out.print("How old are you? "); // prompt int age = console.nextInt(); System.out.println("You typed " + age);
Write a complete program DevryAdmit
with the behavior shown below.
Use the Scanner
to read user input for a student's grade point average and SAT exam score.
A GPA below 1.8 will cause the student to be rejected; an SAT score below 900 will also cause a rejection. Otherwise the student is accepted.
Devry University admission program What is your GPA? 3.2 What is your SAT score? 1280 You were accepted!
Check your answer using Practice-It from the check-mark icon above.
public class AgeCheck { public static void main(String[] args) { int myAge = 19; // I am 19; let me see if I can drive message(myAge); } // Displays message about driving to user based on given age public static void message(int age) { if (myAge >= 16) { System.out.println("I'm old enough to drive!"); } if (myAge <= 16) { System.out.println("Not old enough yet... :*("); } } }
if
and else
in a clumsy way.
Improve the style of the code.
public class AgeCheck { public static void main(String[] args) { int myAge = 19; // I am 19; let me see if I can drive message(myAge); } // Displays a message about driving to user based on given age public static void message(int age) { if (age >= 16) { System.out.println("I'm old enough to drive!"); } else { System.out.println("Not old enough yet... :*("); } } }
AgeCheck
program's message
method with:
// Possibly prints some message(s) to the user based on the given age public static void message(int age) { if (age >= 21) { System.out.println("I can legally purchase alcohol!"); } else if (age >= 17) { System.out.println("I can purchase a ticket to an R-rated movie."); } else if (age >= 16) { System.out.println("I can get my driver's license!"); } }
if
s
and else
s in this method to behave properly.
if
/else
factoringif
/else
. For example:
if (x < 30) { a = 2; x++; System.out.println("CSE 142 TAs are awesome! " + x); } else { a = 2; System.out.println("CSE 142 TAs are awesome! " + x); }
else
went away!)
a = 2; if (x < 30) { x++; } System.out.println("CSE 142 TAs are awesome! " + x);
if
/else
Factoringmain
and run it to make sure it works properly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public class IfOops { public static void main(String[] args) { int a = 7, b = 42; minimum(a, b); if {smaller = a} { System.out.println("a is the smallest!"); } } public static void minimum(int a, int b) { // returns which int is smaller if (a < b) { int smaller = a; } else (a => b) { int smaller = b; } return int smaller; } } |
if
statement should use ()
parentheses, not {}
brackets=
should be ==
smaller
is out of scope herevoid
should be int
=>
should be >=
(or better
yet, no if
test is needed)int
when
returning itint smaller
is out of scope here (declare
outside if
or return directly)public class IfOops { public static void main(String[] args) { int a = 7, b = 42; int smaller = minimum(a, b); if (smaller == a) { System.out.println("a is the smallest!"); } } public staticvoidint minimum(int a, int b) { // returns which int is smaller int smaller; if (a < b) {intsmaller = a; } elseif (a >= b){intsmaller = b; } returnintsmaller; } }
You're thinking about going with your friends to a
movie. Write a Java method seeMovie
that
accepts two parameters: the cost of a ticket in dollars,
and the rating number of stars the movie received out of
5. The method should print how interested you are (very, sort-of, or not).
Use the following criteria:
Write a Java program that draws the following output using a for
loop.
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 } } }
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; } } }
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!