cs 170 java programming 1 week 9: learning about...

40
CS 170 Java Programming 1 Week 9: Learning about Loops

Upload: doantruc

Post on 29-May-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

CS 170

Java Programming 1

Week 9: Learning about Loops

What’s the Plan?

� Topic 1: A Little Review

� ACM GUI Apps, Buttons, Text and Events

� Topic 2: Learning about Loops

� Different kinds of loops

� Using loops to modify Picture objects

� Writing loop functions that work with String objects

� Topic 3: Introducing Animation

� Using loops to animate your GUI objects

Your "IC" or "Lab" Document

� Use Word or OpenOffice to create a new document

� Save the file as IC09.doc (Office 97-2003 compatible)

� Place on your network U: drive or on a thumb drive

� Put your name and today's date at the top of the sheet

� Title it "CS 170 Lab Exercises Week 9"

� Start DrJava and we'll start with a little GUI review

� Open TurtleWorld.java in your week09 folder

Topic 1 (Review)

ACM GUI Apps, Widgets and Events

ACM GraphicsProgram Review

� Notice how ACM GUI apps are different

� Three different import statements

� Inheritance: extends GraphicsProgram

� Two different methods you will override

� The acm.graphics package contains graphical shapes

� Exercise 9.1 – create a GTurtle variable

� Create the variable outside of your methods

� Put the word private in front of it

� This is called an instance variable

Creating Graphical Objects

� Exercise 9.2 – create a GTurtle object

� Put inside init() method (means initialization)

� Initialize GTurtle instance variable (NOT NEW VAR)

� Look up GTurtle docs on class Web site

� Add it to the center of your program's canvas

� Find out the width and height of canvas

� Use width / 2 – half the width of the turtle

� Run and shoot a picture

Using Interactors (aka Widgets)

� The javax.swing package contains interactors

� JButton: push buttons

� JLabel: labels

� JTextField: text input areas

� Exercise 9.3 – create three JButton objects

� Create them inside the init() method

� "Turn Left", "Turn Right", "Move"

� Add them to the SOUTH panel of your program

� Run and snap a screen-shot

Hooking Up Events

� Buttons don't do anything without an event handler

� Event handling is in the java.awt.event package

� For ACM GUI apps, "activate" all buttons in program

addActionListeners(); // bottom of init()

� Respond to Action events with this method

public void actionPerformed(ActionEvent e)

{

// Your code goes here}

Responding to Events

� First, you need to know which button was clicked

� ActionEvent variable has two methods

� e.getActionCommand(): String on button

� e.getSource(): reference to button

� Exercise 9.4 – Activate your turtle

� Get the text on the button

� Use sequential if statements to decide what to do

� Call the methods in your GTurtle variable

� Run, move your turtle around and snap a picture

Other Event Listeners

� We can listen for mouse events as well

� In ACM programs, just add this to your init() method

addMouseListeners(); // bottom of init()

� Respond to different mouse events with these handlers:

� mouseClicked(), mouseMoved(), etc.

� All are void methods that take a MouseEvent parameter

� Exercise 9.5 – hook up mouse events for your program

� When clicked, use setLocation() to move the turtle

Topic 2

Introducing Counted Loops

� A CS term that means repeating a set of actions� Also called repetition or looping

� Statements used in iteration are called loops

� Loops are flow-of-control statements similar to if

� Like the if statement, a loop evaluates a condition

� If the condition is true, a group of actions are performed

� If the condition is false, the actions are skipped

Iteration and Loops

Iteration and Selection

� Iteration is not the same as selection, though

� A loop returns to its test

after performing its actions

� If the test is still true,

then the actions are

performed again

� A selection statement only

performs its actions once

� You cannot replace a loop with a selection statement

Java and Iteration

� Test at the bottom � Test at the top

{

// Loop Body}

{{

// Loop Body// Loop Body}}

Loop TestLoop Test

� Java has three loops: while, do-while, and for� Each is designed to work best in a specific situation

� One difference is where the test is made

{

// Loop Body}

{

// Loop BodyLoop Body}

Loop TestLoop Test

� Not the most useful method of classification� Doesn't give you any empirical guidance for designing

� Better: ask how each loop is controlled

� Two basic methods of loop control� Simplest method relies on a counter

� Called counting or counted loops

� "Repeat these actions 10 times"

� More complex loops test the occurrence of a particular event, or combination of events.

� These are called indefinite or indeterminate loops

Loop Classification

For Loops

� A counted loop is simplest kind of loop

� The loop is controlled by a or counter variable

� Also known as the loop index

� Use it to for "perform this action 10 times"

� Java's for loop specializes in this

for (int idx = 0; idx < 10; idx++){

System.out.println("idx = " + idx);}

The for Loop Syntax

� The for loop has both a header and body (like if)

� Header has 3 expressions: initialize, test, and update

Your Turn

� Exercise 9.6 – Try these in the Interactions pane

� Write a loop that prints 40 asterisks to the screen

� Write a method that prints n asterisks to the screen

� Call your method with 5 and 10

� Write a loop that adds 5 numbers input by the user

Modifying Pictures

� Let's use some loops to modify some Picture objects

� Open your own (640 x 480) picture in the Interactions Pane

� String fname = FileChooser.pickAFile();

Picture p = new Picture(fname);

p.explore();

� Now, find out how large the Picture is and save the info

� int width = p.getWidth();

int height = p.getHeight();

The Pixel class

� The Pixel class models individual pixels in your picture

� Each object of the Pixel class has

� An (x, y) position in a picture (x = horizontal, y = vertical)

� A red, green, and blue value (between 0 and 255)

� We can get a pixel at a specific location in a picture by using the getPixel() method of the Picture class

� Pixel pix1 = p.getPixel(0,0);

Pixel Methods

� Pixels "know" how to do certain things

� You can ask a Pixel for its color values, or change them

� int red = pix.getRed();

pix.setRed(red / 2); // half as much

� You can also ask a Pixel for the entire Color

� Color pc = pix.getColor();

pix.setColor(pc.darker());

� You can ask a Pixel to tell you where it is located

� int x = pix.getX();

Your Turn

� Exercise 9.7 – Let's continue modifying our Picture

� Start by drawing a green line vertically down the center

� import java.awt.* so we can use Color

� Write a loop that starts at 0 and goes until height

� Inside, grab a Pixel from your Picture, using

width / 2 for x and the loop index for y

� Set the Pixel Color to green

� Show the picture again

� When it works, draw a horizontal red line and snap a pic

Nested Loops

� Nested loops let us process all of the pixels in a picture

� Write one loop that processes all rows

� Inside that loop, write another loop that visits the columns

� for (int y = 0; y < height; y++) {

for (int x = 0; x < width; x++) {

Pixel pix = p.getPixel(x, y);

Color col = pix.getColor();

col = col.darker().darker();

pix.setColor(col);

}

}

Your Turn

� Exercise 9.8 – Let's use some nested loops

� Process the upper-left quadrant: make all pixels darker

� Process the lower-right quadrant: make all pixels brighter

� Process the upper-right quadrant: add vertical stripes� Only process every other x position in your loop

� Process the lower-left quadrant: add a checkerboard� If the row is even, process the odd pixels

� If the row is odd, process the even pixels

� Save as a new file name and paste into your IC doc

Just An Example

For Loop Functions

Step 1: The Skeleton

� Same steps for all function problems

� 1. Write the header

� 2. Create a result variable

� 3. Return the result

� 4. Run your tests

Step 2: Loop Through Strings

� Normally String problems require you to visit every

character (or set of characters) in the String

� You can write a "skeleton" for this part too

int len = str.length()

for (int i = 0; i < len; i++)

{

// do your processing here}

Step 3: Processing

� Inside the loop, process characters or substrings

� Use the charAt() or substring() method to

extract

int len = str.length();

for (int i = 0; i < len; i++)

{

// Use only one of these belowchar ch = str.charAt(i);

String sCh = str.substring(i,

i+1);

}

Introducing the while Loop

� Counted loops with for are easy

� All of the pieces are in one place

� The initializer for your counter

� The test expression

� The update expression

� The simpler, general-purpose while loop can

also be used to create counted loops

� It's just not quite as convenient as for

Counted while Loops

� To use the while statement to build a counted loop,

you must do three things:

� 1. Create a counter variable, and initialize it

before the loop is encountered.

� 2. Test the counter variable inside the while

loop's boolean condition expression

� 3. Update your counter at the end of the loop

body. This takes the place of the for loop's

update expression.

A Counted while Skeleton

� Here is a skeleton for building counted while loops:

int counter = 0;

while (counter < 10)

{

// Loop body statementscounter++;

}

� Use this basic structure for many of exercises this week

While Loop Functions

� Exercise 9.10 –mixString in WhileLoopProblems

� Always start with the basic function skeleton

� Notice that these problems require a while loop

� Add basic while loop pattern (skeleton) to code

� Use shorter string for length of variable

� Add character from a to result, then from b

� After loop, see if index is < length� Add remaining characters to end

� Shoot a screenshot of tests passing

Topic 3

Loops and Animation

Animation

� Appearance of motion by changing the shape or position

of objects as a fixed, but rapid rate

� Provides the illusion of motion, similar to movies

� Similar (but different) techniques for applets and ACM

� Four steps:

� 1. Create objects to be animated as instance vars

� 2. Paint object at current location, shape, color

� 3. Call mutator methods to update state of object

� 4. Advance to next frame of animation

Frame-Rate and Skeleton

� Normally want to redisplay from 12-30 frames per sec

� Create constant in terms of milliseconds inside run()

� final int FRAME_RATE = 1000 / 30;

� ACM animation: endless loop inside run() method

public void run() {

advanceOneFrame(); // update objectspause(FRAME_RATE); // wait for next

}

Your Turn

� Let's animate our GTurtle so that it moves automatically

� It's up to you to keep it "on the table"; if it crawls off, it dies

� Add the advanceOneFrame() method

� Inside, move your turtle forward 5 spaces

� Start by adding the skeleton animation loop to run()

� Add the constant FRAME_RATE

� Add a loop that continues while the turtle is visible

� Have to approximate using getX() and getY()

� When the loop ends, display a message box

Finishing Up

� To complete your IC "lab" document:

� Complete Exercise 9.11 in the For Loop lesson, Exercise

9.12 in the While Loop lesson, and Exercises 9.13 in the

Loop Functions lesson, and Exercises 9.14-15 in the

Introducing Animation Lesson.

� Submit to Blackboard when done

� Reading for next week:

� Mediacomp: read Chapter 4 for modifying Pictures

� Gaddis: finish Chapter 3, start Chapter 5

Homework and Quiz

� Homework, Quiz and Assignments

� Deadline is Monday at noon

� 11 homework problems

� 5 for loop functions (similar to exam)

� 5 while loop functions (similar to exam)

� 1 animation, GUI program

� Upload to Assignment Dropbox, press Submit

� Proficiency Quiz 6: Simple for and while loop functions

� Practice on assignments

� You will have ½ hour, assigned seating

Additional Credits

Some material adapted from instructor materials created

by B. Ericson to accompany Introduction to Computing

and Programming with Java: A Multimedia Approach

by M. Guzdial and B. Ericson, released under a Creative

Commons 3.0 Attribution License.