0% found this document useful (0 votes)
108 views79 pages

Blue Pelican Java: Graphical Labs Student Manual

Uploaded by

roya18
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views79 pages

Blue Pelican Java: Graphical Labs Student Manual

Uploaded by

roya18
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Blue Pelican Java

Graphical Labs
Student Manual

Copyright ©, 2008 by Charles Cook;


Refugio, Tx

(all rights reserved)


Table of Contents
BPJ Text
Topic Lesson # Page #

Getting started – Installation of software ………………………. GS-1


Demonstrating GridWorld ……………………………………... DG-1
BugLab 1 – ANDing two Booleans ……………………………. 8 BL 1-1
BugLab 1 Key BL 1-3
BugLab 2 – Using a boolean with if-else ………………………. 9 BL 2-1
BugLab 2 Key BL 2-3
BugLab 3 – Using switch and modulus ………………………... 10 BL 3-1
BugLab 3 Key BL 3-3
BugLab 4 – Using a for loop …………………………………… 11 BL 4-1
BugLab 4 Key BL 4-3
BugLab 5 – Using a while loop ………………………………... 12 BL 5-1
BugLab 5 Key BL 5-3
BugLab 6 – Creating new objects from a class ………………… 15 BL 6-1
BugLab 6 Key BL 6-3
BugLab 7 – Passing arguments to a class constructor …………. 16 BL 7-1
BugLab 7 Key BL 7-3
BugLab 8 – Using data members and the compareTo method … 17 BL 8-1
BugLab 8 Key BL 8-6
BugLab 9 – Using Scanner with Strings, regular expressions …. 17 BL 9-1
BugLab 9 Key BL 9-2
BugLab 10 – Using an array of Strings and Arrays.toString …... 19 BL 10-1
BugLab 10 Key BL 10-3
BugLab 11 – Using an array of objects ………………………… 19 BL 11-1
BugLab 11 Key BL 11-3
BugLab 12 – Using a static data member ……………………… 20 BL 12-1
BugLab 12 Key BL 12-3
BugLab 13 – File input, processing Strings with Scanner ……... 25 BL 13-1
BugLab 13 Key BL 13-3
BugLab 14 – Writing to a file ………………………………….. 26 BL 14-1
BugLab 14 Key BL 14-2
BugLab 15 – Bitwise operations (AND and OR) ……………… 28 BL 15-1
BugLab 15 Key BL 15-3
BugLab 16 – Bitwise operations and Scanner’s findInLine …… 17, 28 BL 16-1
BugLab 16 Key BL 16-3
BugLab 17 – Random numbers, nextInt ……………………….. 30 BL 17-1
BugLab 17 Key BL 17-3
BugLab 18 – Using the selection operator (ternary conditional).. 33 BL 18-1
BugLab 18 Key BL 18-3
BugLab 19 – Two-dimensional arrays …………………………. 35 BL 19-1
BugLab 19 Key BL 19-3
BPJ Text
Topic Lesson # Page #

BugLab 20 – Inheritance, overriding methods …………………. 36 BL 20-1


BugLab 20 Key BL 20-3
BugLab 21 – Using instanceof …………………………………. 36 BL 21-1
BugLab 21 Key BL 21-6
BugLab 22 – Exceptions (try – catch) …………………………. 37 BL 22-1
BugLab 22 Key BL 22-3
BugLab 23 – Recursion 40 ……………………………………... 40 BL 23-1
BugLab 23 Key BL 23-2
BugLab 24 – Using the ArrayList class ………………………... 42, 43 BL 24-1
BugLab 24 Key BL 24-3
BugLab 25 – Using ArrayList and ListIterator ………………… 43, 44 BL 25-1
BugLab 25 Key BL 25-3
BugLab 26 – Sorting an array, compareTo …………………….. 41, 45 BL 26-1
BugLab 26 Key BL 26-4
BugLab 27 – Sorting, using a StringBuffer’s reverse method …. 31, 41 BL 27-1
BugLab 27 Key BL 27-4
BugLab 28 – Sorting with a Comparator object ……………….. 45 BL 28-1
BugLab 28 Key BL 28-4
BugLab29 – Finding the intersection of Sets …………………... 46 BL 29-1
BugLab 29 Key BL 29-4
BugLab 30 – Using a Map object ……………………………… 47 BL 30-1
BugLab 30 Key BL 30-5
GS -1

Getting Started- Installation of Software


Why Graphical Labs?
Blue Pelican’s Graphical Java Labs are, as the name suggests, graphically oriented. However,
they assume no prior knowledge of Java graphics and do not attempt to teach graphics. The
purpose of the graphics is simply to hold the interest of the students. The benefits for a
traditional course on Java are three fold:

• Beginning Java students ARE able to do the labs early in the course even if they are
using a Java textbook like Blue Pelican Java in which the subject of classes and
objects are deferred until later in the course.

• Students are highly motivated by the graphical results of their programs – even
small programs that might only involve a simple if statement.

• Students become accustomed to the Graphics framework (GridWorld) of these labs


and therefore transition easily into the AP Case Study (GridWorld) later in a
CompSci A or Comp Sci AB course.

It’s not a study of Gridworld:


It should be emphasized here that these labs are not a study of GridWorld. The
GridWorld framework need not be understood in order to do the labs. Again, it is simply
there to make the labs more interesting and relevant for the student.

(The remainder of this installation chapter might be uncomfortable for some beginning/
inexperienced students, so it is suggested that the instructor do the installation for each student
computer.)

Installing the Graphical Interface:


In order to do the labs, the GridWorld code must be installed on each student computer.
This is done once, and after that the student largely ignores the complexity of all that code.
He/she just places code for the current lab (if’s, switches, loops, etc.) into the preexisting
graphical framework.

The first step of the installation will be to go to the following College Board web page:

http://www.collegeboard.com/student/testing/ap/compsci_a/case.html

From this page, download the two files labeled as follows:

• Code (zip/238kb) …Create a folder called GridWorldDownloads and place this file
there. Unzip and place the resulting code in a folder named C:\GridWorldCode.

• Installation guide (.pdf/172kb) …Also place this file in the GridWorldDownloads


folder. This document will give instructions for how to make the gridworld.jar file
available as a library to your particular IDE. The following IDE’s are supported:

o Eclipse 3.1
GS -2

o BlueJ 2 …The DVD that accompanies this document provides specific


instructions and a demonstration for this particular IDE.

o JCreator 3.5 (Windows only) From the menu select Project | Project
Properties. Click the Required Libraries tab and click New. In the Set Library
dialog box, click the Add button, select Add Archive, then browse to add the
JAR file that resides in the GridWorldCode folder. Give the new library a
name. Finally, click the checkbox for the new library and click OK.

o JJ (Windows only)

o TextPad 5.0 (Windows only)

Creating two necessary classes:


The GridWorld code downloaded and installed above make up the necessary background
code that the student never sees while doing the labs. There are, however, two class files
that must be part of every lab project. These are detailed below and are also, for
convenience, included on the DVD (in the BasicBug folder) that accompanies this document.

The BasicBug class (file name BasicBug.java) is as follows:


import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{

//Unique code for each lab to be placed here

The BasicBugRunner class (file BasicBugRunner.java) is as follows:


//This class will not compile until the BasicBug class first compiles.
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
public class BasicBugRunner
{
public static void main(String args[])
{
ActorWorld world = new ActorWorld( );
BasicBug bug1 = new BasicBug( );
bug1.setColor(Color.ORANGE);

Rock rock1 = new Rock( );


GS -3

rock1.setColor(Color.BLACK);

world.add(new Location(5,3), bug1);


world.add(new Location(1, 3), rock1);
world.show( );
}
}

Place these two source code files (BasicBugRunner.java and BasicBug.java) on your hard
drive in a sub folder of GridWorldProjects named BasicBug. The hierarchal folder structure is
as follows:

C:
GridWorldProjects
BasicBug
BasicBugRunner.java
BasicBug.java
.
.
… other student project folders created as the
… course progresses
.
.

What’s on the Hard drive:


At this point the following folders should be on your hard drive:
GridWorldCode
… several sub folders and the all-important Jar file …

GridWorldDownloads

GridWorldProjects
BasicBug
DG-1

Demonstrating GridWorld

Run the code:


In this chapter we will get a feeling for how GridWorld works. To do this, import
the two files in the BasicBug folder into a project in your IDE, compile both
classes, and then execute the main method of the BasicBugRunner class. To run
main in BlueJ, right-click on the BasicBugRunner class icon and then click on
void main. The following graphical interface will appear (If not, it may only
appear as an item on the task bar. Just click on it to make it display.)

Fig DG-1.
GridWorld,
BasicBugRunner
graphical interface

Experiment:
Click on the Step button a couple of times and observe the bug moving forward.
Now click on any empty cell and get a display similar to the following:

Fig DG-2. The result of


clicking on an empty cell.
DG-2

Click on one of the items in the drop-down menu and add another bug, flower, or
rock to the grid at this grid location. Continue experimenting with the controls in
this graphic interface and the following facts will soon become apparent:

• Each time the Step button is clicked, the Bug advances one cell, leaving
behind a flower of the same color as the bug. Each time the bug advances,
each flower in it’s “flower trail” becomes progressively darker, thus
showing their age.

• If the bug encounters an obstacle (the black rock in Fig. DG-1) or the edge
of the grid, instead of moving forward, it turns 45 degrees clockwise. If it
still can’t move, it turns another 45 degrees. This turning continues until it
can move forward.

• A bug does not consider a flower to be an obstacle. When moving forward


into a flower location, the bug “eats” the flower and it disappears.

• Clicking the Run button results in the bug continuing to step with a delay
between steps determined by the Slow/Fast slider.

• The Stop button is only active after Run is clicked. It stops the Run
process.

Don’t use them:


It is recommended that the World and Location menu items at the top of the
interface not be used with these labs.

Making changes:
Clicking on an object such as a bug, rock, or flower results in the following drop-
down menu.

Fig DG-2. The drop-


down menu that results
from clicking on a Bug,
Rock, or Flower.
DG-3

The drop-down menu:


The items in this object drop-down menu are all methods of that object.
Clicking on one of these items is, in effect, equivalent to calling that
method. The menu items seen here are peculiar to the object selected. The
methods available for the Bug, Rock, and Flower are all different. If
parameters are required when selecting a method, a dialog box will appear
for their entry.

Direction and coordinate conventions:


Some of the methods that can be selected in the above menu samples will call for
directions, and GridWorld has its own conventions. Unlike regular mathematics
where East is 0 degrees and positive angles rotate counterclockwise, here in
GridWorld, north is 0 degrees and positive angles rotate clockwise.

Why did the creators of this class do it that way? Supposedly, it is because this is
conventionally how navigation of ships and aircraft is done (north is 0 degrees
with positive angles rotating clockwise.), and here in GridWorld we are
“navigating” the grid.

There is yet another difference from conventional mathematics where it is


customary to think of the origin as being in the center (sometimes the lower left
corner) with the positive vertical axis (the “Y” axis) proceeding upward: not so
in GridWorld. The origin (0,0) is the cell in the upper left corner with the
positive direction of the vertical axis proceeding downward. The positive
direction of the horizontal axis is still to the right as it is conventionally.

Continue to experiment:
Continue to experiment by creating new objects in the grid. Then click on those
objects to change their properties. The student should become aware that this is an
effective learning technique – experimenting.
BL 1 - 1

BugLab 1 – ANDing two booleans (Blue Pelican Java Lesson 8)


(Teacher: Although students may not yet be well versed with the meaning of the term
“method”, it is used below. As a result, hopefully, the student will become accustomed to
hearing the term and feel more comfortable when the creation of methods is explored in
future lessons.)

Create the project:


Create a new project (named BugLab1) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:

Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Look at the source code:


Next, open the source code for the BasicBug class (we will not need to modify the
BasicBugRunner class). The code for this class should read as follows:

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
//Unique code for each lab to be placed here
}

Shortly, we will be replacing the rem with code of our own using a boolean AND
within an if statement.

Two GridWorld methods:


Just as main is a “method”, GridWorld has three methods that we will find useful
in this lab. We need not understand how they work. All we need to know is that
they do work and that they produce the results described below.

canMove( )
All we need to know is that this returns a boolean. It will be true if the bug
sees no obstacle in front of it. A false will be returned if the bug can’t
move forward; perhaps another bug or rock is in its path, or it’s at the edge
of the grid.

move( )
This method simply moves the bug forward one cell.

turn( )
The bug faces a new direction by turning 45 degree clockwise.
BL 1 - 2

Make the following changes to BasicBug:

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
public void act( ) // Executes each time the Step button is clicked.
{
if( canMove( ) ) // Is it ok to move?
{
move( ); //canMove( ) is true, so move forward.
}
else
{
turn( ); //Turn 45 deg clockwise if move is blocked.
}
}
private int count = 0; //Use count to determine the number of steps.
}

At this point, do not concern yourself with the peculiarities concerning the
position and syntax of private int count. Just simply think of count as a variable
with which we will count-off three steps before turning.

The task at hand:


With the code above, the bug moves forward with one click of the Step button and
rotates 45 degrees clockwise when it can no longer move in its forward direction
due to the presence of a rock or another bug, or when the edge of the grid is
encountered.

Our job here is to replace the boolean canMove( ) with the appropriate boolean
expression that will look for an additional reason to turn the bug. What we want
is for the bug to only move forward if both canMove( ) is true and the bug has
moved no more than three spaces since beginning its movement or since the last
turn.

Hint: Use a boolean AND in the parenthesis of the if. Use the ++ operator to
increment count appropriately.
BL 2 - 1

BugLab 2 –Using a boolean with if-else (Blue Pelican Java Lesson 9)


(Teacher: Although students may not yet be well versed with the meaning of the term
“method”, it is used below. As a result, hopefully, the student will become accustomed to
hearing the term and feel more comfortable when the creation of methods is explored in
future lessons.)

Create the project:


Create a new project (named BugLab2) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:

Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Look at the source code:


Next, open the source code for the BasicBug class (we will not need to modify the
BasicBugRunner class). The code for this class should read as follows:

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
//Unique code for each lab to be placed here
}

Shortly, we will be replacing the rem with code of our own using a boolean and
an if-else statement.

Three GridWorld methods:


Just as main is a “method”, GridWorld has three methods that we will find useful
in this lab. We need not understand how they work. All we need to know is that
they do work and that they produce the results described below.

canMove( )
All we need to know is that this returns a boolean. It will be true if the bug
sees no obstacle in front of it. A false will be returned if the bug can’t
move forward; perhaps another bug or rock is in its path, or it’s at the edge
of the grid.

move( )
This method simply moves the bug forward one cell.

turn( )
The bug faces a new direction by turning 45 degree clockwise.
BL 2 - 2

The task at hand:


Currently, the bug moves forward with one click of the Step button and rotates 45
degrees clockwise when it can no longer move in its forward direction.

Our job here is to replace the rems in the code below so as to modify the bug’s
behavior as follows:

For each click of the Step button move forward one cell if it’s ok to move;
otherwise turn 135 degrees (using turn( ) several times). Then repeat the
entire process. Thus, it is possible to move forward two cells with a single
click of the Step button. Notice that with this scheme it is also possible for no
move to be made if the bug is sufficiently blocked.

It is important to know that all of the code inside the act method executes
each time the Step button is clicked.

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
public void act( ) //Executes each time the Step button is clicked.
{
//Use canMove( ) to decide if it’s ok to move. Use move( )
//to move forward one cell. Use turn( ) to turn. Recall that a
//single execution of turn( ) is just 45 deg clockwise.
}
}
BL 3 - 1

BugLab 3 – Using switch & modulus (Blue Pelican Java Lesson 10)
(Teacher: Although students may not yet be well versed with the meaning of the term
“method”, it is used below. As a result, hopefully, the student will become accustomed to
hearing the term and feel more comfortable when the creation of methods is explored in
future lessons.)

Create the project:


Create a new project (named BugLab3) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:

Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Look at the source code:


Next, open the source code for the BasicBug class (we will not need to modify the
BasicBugRunner class). The code for this class should read as follows:

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
//Unique code for each lab to be placed here
}

Shortly, we will be replacing the rem with code of our own using a switch
structure.

Three GridWorld methods:


Just as main is a “method”, GridWorld has three methods that we will find useful
in this lab. We need not understand how they work. All we need to know is that
they do work and that they produce the results described below.

canMove( )
All we need to know is that this returns a boolean. It will be true if the bug
sees no obstacle in front of it. A false will be returned if the bug can’t
move forward; perhaps another bug or rock is in its path, or it’s at the edge
of the grid.

move( )
This method simply moves the bug forward one cell.

turn( )
The bug faces a new direction by turning 45 degree clockwise.
BL 3 - 2

Make the following changes to BasicBug:

import info.gridworld.actor.Bug;
import java.awt.Color;
public class BasicBug extends Bug
{
public void act( ) // Executes each time the Step button is clicked.
{
if( canMove( ) ) // Is it ok to move?
{
move( ); //canMove( ) is true, so move forward.
}
else
{
turn( ); //Turn 45 deg clockwise if move is blocked.
}
}
private int count = 0; //Use count to determine the number of steps.
}

At this point, do not concern yourself with the peculiarities concerning the
position and syntax of private int count. Just simply think of count as a variable
that counts the number of steps taken.

The task at hand:


Currently, the bug moves forward with one click of the Step button and rotates 45
degrees clockwise when it can no longer move in its forward direction.

Our job here is to keep a running count of the number of steps taken by the bug
(by incrementing count appropriately) and to change the color of the bug
(depending on which step it is on) according to the following rules:

After the 1st step, change the bug to a blue color, green after the 2nd step,
yellow after the 3rd step, red after the 4th step, and back to orange (the
bug’s original color) after the 5th step. Continue by repeating this cycle.
Accomplish the color changes with setColor(Color.GREEN), etc.

Make further modifications to BasicBug by incrementing count in the appropriate


place. Then use the modulus operator and a switch structure to change the color of
the bug as described above.
BL 4 - 1

BugLab 4 – Using a for loop (Blue Pelican Java Lesson 11)


(Teacher: Although students may not yet be well versed with the meaning of the term
“method”, it is used below. As a result, hopefully, the student will become accustomed to
hearing the term and feel more comfortable when the creation of methods is explored in
future lessons.)

Create the project:


Create a new project (named BugLab4) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:

Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Look at the source code:


Next, open the source code for the BasicBug class (we will not need to modify the
BasicBugRunner class). Modify the code for this class as follows:

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
public void act( ) //Executes each click of the Step button.
{
if( canMove( ) )
{
move( );
}
else
{
turn( );
}
}
}

Three GridWorld methods:


Just as main is a “method”, GridWorld has three methods that we will find useful
in this lab. We need not understand how they work. All we need to know is that
they do work and that they produce the results described below.

canMove( )
All we need to know is that this returns a boolean. It will be true if the bug
sees no obstacle in front of it. A false will be returned if the bug can’t
BL 4 - 2

move forward; perhaps another bug or rock is in its path, or it’s at the edge
of the grid.

move( )
This method simply moves the bug forward one cell.

turn( )
The bug faces a new direction by turning 45 degree clockwise.

The task at hand:


Currently, the bug moves forward with one click of the Step button and
rotates 45 degrees clockwise (using the turn method) when it can no
longer move in its forward direction.

Our job here is to make the bug turn 45 degree counter clockwise when it
can no longer move in its forward direction. This will be done by
replacing the single turn in the code above with multiple turns. These
multiple 45 degree clockwise turns should bring the bug to the eventual
direction that is equivalent to a single turn of 45 degree counter clockwise.

Instead of replacing the single turn in the code above with multiple turn’s,
create a for loop that executes turn the appropriate number of times.
BL 5 - 1

BugLab 5 – Using a while loop (Blue Pelican Java Lesson 12)


(Teacher: Refer to previous labs for a detailed discussion of the various GridWorld
methods (act, canMove, move, & turn) used in these labs. If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab5) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:

Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Look at the source code:


Next, open the source code for the BasicBug class (we will not need to modify the
BasicBugRunner class). The code for this class should read as follows:

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
//Unique code for each lab to be placed here
}

Enter act method skeleton:


import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
public void act( ) // Executes each time the Step button is clicked.
{

}
}

The task at hand:


Currently, the bug moves forward with one click of the Step button and rotates 45
degrees clockwise when it can no longer move in its forward direction.

Our job here is to redo Lab2 in which we “tried” to make the bug move forward
two times with each click of the step button. There we discovered that we were
unable to guarantee two moves since with each attempted move we might have
needed to turn the bug, instead. Now that we have the while loop in our arsenal of
Java weapons, it is possible to guarantee two moves with each Step button click.
BL 5 - 2

Hint: In the act method place a while loop that stays in the loop as long as
canMove is false, and inside the loop place the turn method. When canMove is
true, the loop is exited and it is safe to move the bug. This all ensures that the first
move will definitely be done after any and all necessary turns. Repeat the entire
process to ensure the second move.
BL 6 - 1

BugLab 6 – Creating new objects (Blue Pelican Java Lesson 15)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab6) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
Modify the source code for BasicBug as shown below. This will cause the bug to
exhibit the default behavior (moving forward one cell for each click of the Step
button or turning clockwise 45 degree if a move is not possible):

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
public void act()
{
if( canMove( ) )
{
move( );
}
else
{
turn( );
}
}
}

The task at hand:


Our job here is to modify the BasicBugRunner class so as to produce two bugs
and a rock as shown below in Fig.BugLab6–1. A magenta bug should be located
in row 1, column 0. A red rock should be in row 3, column 1. A green bug should
be in row 3, column 4.

Notice that rows are numbered from top to bottom with 0 being the index of the
top row. Columns are numbered from left to right with 0 being the index of the
far left column.
BL 6 - 2

Fig.BugLab6-1
Initial positions of the three
objects.

The existing code for BasicBugRunner is shown below. Study it to see how the
bug1 and rock1 objects are created and placed in the grid at certain locations.
Then in a similar way modify the code to produce the three colored objects in the
locations specified above.

//This class will not compile until the BasicBug class first compiles.
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
public class BasicBugRunner
{
public static void main(String args[])
{
ActorWorld world = new ActorWorld( );
BasicBug bug1 = new BasicBug( ); //Create and set color of bug1
bug1.setColor(Color.ORANGE);

Rock rock1 = new Rock( ); //Create and set color of rock1


rock1.setColor(Color.BLACK);

world.add(new Location(5,3), bug1); //Add to grid and set location


world.add(new Location(1, 3), rock1);
world.show( );
}
}
BL 7 - 1

BugLab 7 – Passing arguments to a constructor (Blue Pelican


Java Lesson 16)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab7) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
Modify the source code for BasicBug as shown below. This will cause the bug to
exhibit the default behavior (moving forward one cell for each click of the Step
button or turning clockwise 45 degree if a move is not possible):

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
public void act( )
{
if( canMove( ) )
{
move( );
}
else
{
turn( );
}
}
}

The task at hand:


Our job here is to modify the both the BasicBug and BasicBugRunner classes so
as to accommodate a constructor in BasicBug.

Creating the BasicBug constructor:


Create a constructor for the BasicBug class that will receive as parameters, a
Color object and an int type variable. Then provide the internal code for the
constructor as indicated by the following:
BL 7 - 2

public BasicBug(Color clr, int numTurns)


{
//Use clr with the setColor method to set the bug’s color.
//Use numTurns to iterate through a for-loop in which the
//turn method is executed each time.
}

Notice that at the time of creation of a BasicBug object, this constructor


allows us to set the color of the bug and to orient the bug in a new direction
by turning a specified number of times (each turn is 45 degrees).

Add another import:


To the BasicBug class add the following import so as to accommodate the
use of the Color type:
import java.awt.Color;

Adjusting the BasicBugRunner code:


The following line of code in BasicBugRunner should be modified to pass
to the BasicBug constructor, a Color object (Color.GREEN) and an integer
(3) specifying the number of times to initially turn the newly created
BasicBug object.

BasicBug bug1 = new BasicBug( ?, ? );

Run the main method in BasicBugRunner and the resulting display should be as
follows (notice the green bug turned 45 X 3 = 135 degrees):

Fig. BugLab7-1 Initial position


and orientation of the bug &
rock.
BL 8 - 1

BugLab 8 – Data members and compareTo (Blue Pelican Java


Lesson 17)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab8) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Create BasicBugB:
Modify the source code for BasicBug and rename it BasicBugB as shown below.
This will cause the bug to exhibit the default behavior (moving forward one cell
for each click of the Step button or turning clockwise 45 degree if a move is not
possible). Notice that the constructor allows the bug to have a name (bugName):
import info.gridworld.actor.Bug;
import java.awt.Color;
public class BasicBugB extends Bug
{
public BasicBugB(String nm) //Constructor
{
bugName = nm;
}

public void act()


{
if( canMove() )
{
move();
}
else
{
turn();
}
}
public String bugName;
}

Create BasicBugA:
Create another class called BasicBugA as shown below (just copy and paste):
BL 8 - 2

import info.gridworld.actor.Bug;
import info.gridworld.grid.Location;
import info.gridworld.grid.Grid;
import info.gridworld.actor.*;
public class BasicBugA extends Bug
{
public BasicBugA(String nm)
{
name = nm;
}

public void act( )


{
if( canMove( ) )
{
move( );
}
else
{
Location locMe = getLocation( );
Location locNeighbor = locMe.getAdjacentLocation(getDirection( ));
Grid<Actor>gr = getGrid( );
if(gr.isValid(locNeighbor))
{
Actor adjacentNeighbor = gr.get(locNeighbor);
if(adjacentNeighbor instanceof BasicBugB)
{
//There is a BasicBugB object directly in front of us
BasicBugB bbb= (BasicBugB)adjacentNeighbor;
String adjacentBugName = bbb.bugName;

//Modifications go here
}
else
turn( );
}
else
turn( );
}
}
public String name;
}
Do not be concerned with all the complicated looking code in bold. All it does is
determine if the cell directly in front of our BasicBugA object contains a BasicBugB
object. If so, the name of that BasicBugB object is stored in adjacentBugName.
BL 8 - 3

The task at hand:


Our job here is to modify the above code (where it says Modifications go here)
so as to cause our bug (BasicBugA) to turn 180 degree if there is a BasicBugB
object directly in front of us and if our name is alphabetically less than the
name of the BasicBugB object; otherwise, do just the normal single turn of 45
degrees.

To accomplish this use compareTo in an if statement to compare the name


of our bug (name) to the name of the BasicBugB object (adjacentBugName).

Adjusting the BasicBugRunner code:


Modify (just copy and paste) the following BasicBugRunner class so as to
produce two separate bugs; a BasicBugA object and a BasicBugB object.
Notice that the name data member for BasicBugA is set to “Buster Bug” and
that the bugName data member for BasicBugB has been set to “Nasty Bug”.

//This class will not compile until the other two classes first compile.
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
public class BasicBugRunner
{
public static void main(String args[])
{
ActorWorld world = new ActorWorld( );
BasicBugA bug1 = new BasicBugA("Buster Bug");
bug1.setColor(Color.RED);

BasicBugB bug2 = new BasicBugB("Nasty Bug");


bug2.setColor(Color.GREEN);

Rock rock1 = new Rock( );


rock1.setColor(Color.BLACK);

world.add(new Location(5,3), bug1);


world.add(new Location(1,0), bug2);
world.add(new Location(1, 4), rock1);
world.show( );
}
}

Run the main method in BasicBugRunner and the resulting display should be as
follows:
BL 8 - 4

Fig. BugLab8-1 Initial position


and orientation of the two bugs
& rock. (Green bug is upper
left.)

Testing the code:


Advance the bugs by clicking on the Step button until their positions are as shown
in Fig.BugLab8-2 on the following page. Remember that the red bug (lower one)
is of BasicBugA type and is named, “Buster Bug”. It is alphabetically less than the
other bug whose name is “Nasty Bug”.

Now click on the red bug (right one) and then select setDirection. Enter 270 in the
resulting dialog box so as to face this BasicBugA bug toward the left. The two
bugs should now be facing each other. Since our red bug’s name is alphabetically
less than the name of the left bug, the code should tell him to turn 180 degrees and
retreat.

Click the Step button and this should be observed to happen.

What change would you make to the code so as to cause the BasicBugA object to
retreat when its name is alphabetically greater than the other bug’s name?

Continue to experiment by moving the bugs’ locations and directions and see if
all the rules we have established are being followed.
BL 8 - 5

Fig. BugLab8-2 Final position


of the bugs where the prescribed
behavior can be tested.
BL 9 - 1

BugLab 9 – Using Scanner with Strings, regular expressions


(Blue Pelican Java Lesson 17)
(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab9) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

No need to modify BasicBug:


The BasicBug contains no code. This is not a problem since it inherits the Bug
class and that inherited class provides the needed act method with the default
behavior using the canMove, move, and turn methods. (Notice extends Bug in the
class signature. Inheritance is discussed extensively in Lesson 36.)

The toString method:


Execute the main method in BasicBugRunner, click on the bug, select the toString
method, and obtain something similar to that shown in Fig. BugLab9-1 below:

Fig. BugLab9-1 Accessing


the toString method of a
bug.
BL 9 - 2

The returned String is of interest to us in this lab and for the particular location
shown in Fig. BugLab9-1 is:

BasicBug[location=(2, 0),direction=270,color=java.awt.Color[r=255,g=200,b=0]]

The task at hand:


Consider the BasicBugRunner class:

//This class will not compile until the BasicBug class first compiles.
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
public class BasicBugRunner
{
public static void main(String args[])
{
ActorWorld world = new ActorWorld( );
BasicBug bug1 = new BasicBug( );
bug1.setColor(Color.ORANGE);

Rock rock1 = new Rock( );


rock1.setColor(Color.BLACK);

world.add(new Location(5,3), bug1);


world.add(new Location(1, 3), rock1);
world.show( );
//Modifications go here.
}
}

In the area labeled, “Modification go here”, insert code that will manipulate the
returned String mentioned above, and then print to the console screen a summary
of its contents in exactly the following format:

location=(2, 0)
direction=270
color=[r=255,g=200,b=0]

Use Scanner to parse the String into three sections and then further refine those
pieces as shown above. Build an appropriate delimiter for your Scanner object
using regular expressions. For the sake of Scanner, remember to import
java.util.*.
BL 10 - 1

BugLab 10 – Using an array of Strings & Arrays.toString,


(Blue Pelican Java Lesson 19)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab10) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
The BasicBug class should be changed to include the following:

import info.gridworld.actor.Bug;
import info.gridworld.grid.Location; //Necessary for the Location object below
import java.util.*;
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
Location loc = getLocation( );
int r = loc.getRow( ); //r and c are the row and column to
int c = loc.getCol( ); //which we just moved.
step++;
//<#1>
}
else
{
turn( );
}

}
//<#2>
public int step = 0; //Keeps a running count of the steps.
}
BL 10 - 2

The task at hand:


In this lab we are to keep a running count of what step number we are on. The
count is kept in the step data member in the code above. Additionally create a
another data member, String history[], dimensioned to hold 10 elements in the
area labeled <#2> above.

For each move, store into this array the row and column number of the new cell to
which we moved. Each element of the String array is formatted with a parenthesis
surrounding row and column numbers that are, in turn, separated by a comma: for
example, “(12, 3)”. Notice in the code above that the row and column are already
provided in the variables r and c.

As the count variable step advances, use it as the index for storing the formatted
row-column position into the array. Then print the array using Arrays.toString as
follows (place all this code in the <#1> area above):

System.out.println( Arrays.toString(history) );

In Fig BugLab10-1 below we see four printouts of the resulting history array after
each of four executions of move. After the first move the bug is in row 4, column
3 and after the fourth move, it is in row 1, column 4. Notice the first element of
the history array is still null since we are not yet making provisions for entering
data for the starting position.

Fig. BugLab10-1 The


history array after four
moves. The first row is the
array after the first move,
the second row after the
second move, etc.

Modify BasicBugRunner:
Add code to the bottom of the BasicBugRunner class so as to fill the element of
the String array at index 0 with the initial position of the bug.
BL 11 - 1

BugLab 11 – Using an array of objects, (Blue Pelican Java Lesson


19)
(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab11) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

The task at hand:


In this lab we are to dimension an array of five BasicBug objects in the
BasicBugRunner class. Then initialize each and use the setColor method to
establish the color of each. Get rid of all references to the bug1 object but leave
the Rock object. Make no changes to the BasicBug class. It has no code at all: it
simply inherits code from the Bug class via extends Bug.

Set up a for-loop at the bottom of BasicBugRunner to add each element of the


BasicBug array to the grid (using world.add) while establishing a “staggered”
appearance as shown below. The bug object of index 0 is the top-left bug (row 5,
column 2).

Fig. BugLab11-1 Initial staggered


appearance of the array of bug
objects.
BL 12 - 1

BugLab 12 – Using a static data member,


(Blue Pelican Java Lesson 20)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab12) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
Start with the following default code in the BasicBug class:
public void act()
{
if(canMove( ))
{
move( );
}
else
{
turn( );
}
}

Create two state variables in BasicBug, both integers:


objectCount should be static and initialized to 1.

numTurns should only be declared. It will be initialized in the constructor.

Next, create a constructor in which numTurns is initialized to the current value of


objectCount. Then increment objectCount. Since it is static, its value is
incremented every time the creation of a new BasicBug object executes the
constructor.

The task at hand:


In this lab we are to create several BasicBug objects in BasicBugRunner where
each turns a different number of times when canMove is false. The number of
turns to be executed is determined by the value of the numTurns data member
that is unique for each bug object.
BL 12 - 2

Further modify BasicBug so as to cause numTurns turns to be executed when


canMove is false. In BasicBugRunner, create bug1, bug2, and bug3 objects from
the BasicBug class and position them randomly in the grid. The first object
created should turn only once when encountering an obstacle, the second one
should turn twice, and the third one three times. Run main in BasicBugRunner to
verify that this does indeed happen.
BL 13 - 1

BugLab 13 – File input, processing Strings with Scanner


(Blue Pelican Java Lesson 25)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab13) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Create a text file:


In the folder created for this project, create a text file (using NotePad or
WordPad) named data_Lab13.txt with the following content:

2, 5
4, 3

The task at hand:


In this lab we are to input this text file and then in the BasicBugRunner class, use
this data to position two BasicBug objects on the grid. The given data indicates
that we are to create a BasicBug object (call it bug1) and add it to the grid at the
location given by row 2, column 5. Then create another BasicBug object (call it
bug2) and place it at row 4, column 3.

To input the file, place the following code in the BasicBugRunner class prior to
where world.add is used to add the two BasicBug objects to the grid.

Scanner sf = new Scanner( new File("data_Lab13.txt ") );


int maxIndx = -1; //-1 so when we increment below, first indx is 0
String text[] = new String[100]; //to be safe, declare more than we need
while(sf.hasNext( ))
{
maxIndx++;
text[maxIndx] = sf.nextLine( ) ;
}
sf.close( );

Notice that by having placed data_Lab13.txt in the same folder as our project,
there is no need to reference it with a path. The use of File makes it necessary
to place throws IOException at the end of the main method signature. It will also
BL 13 - 2

be necessary to import java.util.* and java.io.*.

After the execution of this code the contents of the text[] array will be as follows:

text[0] contains the String, “2, 5”


text[1] contains the String, “4, 3”

Next, create a new Scanner object and set an appropriate delimiter. Parse these
two Strings into the integer variables r1, c1, r2, and c2, and then use these
variables to position bug1 and bug2 in the grid with world.add.

There is no need to modify the BasicBug class. It inherits the needed code from
Bug via extends Bug.

Run main to see the properly positioned bug objects as shown below.

Fig.BugLab13-1 bug1 (orange,


upper right) properly positioned at
2, 5 and bug2 (green, lower left)
properly positioned at 4,3.
BL 14 - 1

BugLab 14 – Writing to a file, (Blue Pelican Java Lesson 26)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab14) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBugRunner:
At the very bottom of the BasicBugRunner class, add the following code that will
create and write to a file on your hard disk:
FileWriter fw = new FileWriter(<#1>); //Student adds code here.
PrintWriter output = new PrintWriter(fw);
<#2> //Student adds code here.
output.close( );
fw.close( );

The presence of FileWriter and PrintWriter will make it necessary to import the
java.io.* package. Also, the possibility of a checked exception make it necessary
to append throws IOException to the main method signature.

There is no need to modify the BasicBug class. It inherits the needed code from
Bug via extends Bug.

The task at hand:


In the area of <#1> place file name outputFile.txt and the path where you would
like to store that file. Remember to use “\\” where a “\” would normally be used in
the path name. To store the file in this project’s folder, provide just the file name
and omit the path.

In the area of <#2> use the println method of the output object to describe first the
bug1 object and then the rock1 object. The description of each is provided with
their toString methods. Thus the area of <#2> should consist of two lines of code.

Run main and then from within Windows Explorer, check the contents of
outputFile.txt. It should be as follows:

BasicBug[location=(5, 3),direction=0,color=java.awt.Color[r=255,g=200,b=0]]
info.gridworld.actor.Rock[location=(1, 3),direction=0,color=java.awt.Color[r=0,g=0,b=0]]
BL 15 - 1

BugLab 15 – Bitwise operations, (Blue Pelican Java Lesson 28)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab15) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
Make the following changes to BasicBug. All additional code for this lab will be
done in the area of <#1> below where the bug’s color will be changed when a
move is not possible and a turn is being executed.

import info.gridworld.actor.Bug;
import java.util.*; //Necessary for Scanner
import java.awt.Color; //necessary for the Color class to be used below
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
String s = toString( );
//sample,
//"BasicBug[location=(2,3),direction=45,color=java.awt.Color[r=255,g=200,b=0]]"

<#1> //Change color here

}
}
}

The task at hand:


From the String produced by the toString method, extract the red, green, and blue
BL 15 - 2

components of the bug’s color. This can be done in sections as follows in the area
of <#1> in the code above:

int i = s.indexOf("[r="); // The "[" is necessary or it will find "r=" preceeding awt
s = s.substring(????); //Chop off everything prior to "r=".
//sample result , "r=255,g=200,b=0]]"
s = s.substring(?????); //Remove the trailing two square brackets.
//sample result, "r=255,g=200,b=0"

Scanner sc = new Scanner(s);


sc.useDelimiter(",");

//Red color
String rString = sc.?????;
rString = rString.substring(??); //Remove "r="
int r = ?????; //Convert to int

//Green color
String gString = sc.?????;
gString = gString.substring(??); //Remove "g="
int g = ?????; //Convert to int

//Blue color
String bString = sc.?????;
bString = bString.substring(??); //Remove "b="
int b = ?????; //Convert to int

The color component values of r, g, and b will now be used as follows:

Bitwise AND the r, g, and b values and then bitwise OR that result with
the decimal equivalent of the binary String, "10101010". The final result then
becomes the new value for int newValue that establishes the new color of the bug
as follows:

Color clr = new Color(newValue, newValue, newValue);


setColor(clr); //Set new color for bug

Run main, step the bug, and observe the color change as the bug turns.
BL 16 - 1

BugLab 16 – Bitwise operations & the findInLine method,


(Blue Pelican Java Lesson 17, 28)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab16) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
This lab is essentially the same as BugLab15 except the color portion of the String
is to be located with Scanner’s findInLine method. Change the BasicBug class as
follows and note that further changes will be made in the area of <#1>:

import info.gridworld.actor.Bug;
import java.util.*; //Necessary for Scanner
import java.awt.Color; //Necessary for the Color class used below
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
String s = toString( );
//sample, "BasicBug[location=(2, 3),direction=45,color=java.awt.Color[r=255,g=200,b=0]]"

s = s.substring(0, s.length( )-2); //Remove the trailing two square brackets.


//sample, "BasicBug[location=(2, 3),direction=45,color=java.awt.Color[r=255,g=200,b=0"

Scanner sc = new Scanner(s);


<#1>

sc.useDelimiter(",");
BL 16 - 2

//Red color
String rString = sc.next( );
rString = rString.substring(2); //Remove "r="
int r = Integer.parseInt(rString); //Convert to int

//Green color
String gString = sc.next( );
gString = gString.substring(2); //Remove "g="
int g = Integer.parseInt(gString); //Convert to int

//Blue color
String bString = sc.next( );
bString = bString.substring(2); //Remove "b="
int b = Integer.parseInt(bString); //Convert to int

String s1 = "10101010";
int val_s1 = Integer.parseInt(s1,2); //Covert the binary String to decimal
int newValue = (r & g & b) | val_s1;

Color clr = new Color(newValue, newValue, newValue);


setColor(clr); //Set new color for bug
}
}
}

The task at hand:


Insert code in the area of <#1> above using the findInLine method of the Scanner
class. Application of that method should place the scan position between “[“ and
“r”. From that point on, the program remains the same as in the solution to
BugLab15.
BL 17 - 1

BugLab 17 – Random numbers, (Blue Pelican Java Lesson 30)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab17) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
Make the following changes to BasicBug. All additional code for this lab will be
done in the area of <#1> below where the bug’s color and direction will be
randomly changed. Note that this is the area where a turn of 45 degrees was
executed in earlier labs.

import info.gridworld.actor.Bug;
import java.util.*; //Necessary for Random
import java.awt.Color; //Necessary for the Color class to be used below
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
<#1> //Randomly change color and direction here

}
}
}

The task at hand:


The new color of the bug is to be set with the setColor method as follows where r,
g, and b are all random integers between 0(inclusive) and 255(inclusive):

Color clr = new Color(r, g, b);


setColor(clr);
BL 17 - 2

The new direction of the bug is determined with setDirectin(dir) where dir is a
random integer between 0(inclusive) and 359(inclusive). Recall that as a
navigational angle, north is 0, east is 90, etc.

Run main, step the bug, and observe the color and direction randomly change each time
the bug needs to turn.
BL 18 - 1

BugLab 18 – Selection operator (ternary conditional),


(Blue Pelican Java Lesson 33)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab18) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
Make the following changes to BasicBug. Determine the location of the bug and
then determine from its location how many times to turn the bug if a move is
blocked.

import info.gridworld.actor.Bug;
import info.gridworld.grid.Location; //Necessary for Location class below
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
Location loc = getLocation( ); //Get the Location object describing the
int row = loc.getRow( ); //current position of the bug.
int col = loc.getCol( );

<#1>

for(int j = 0; j < numTurns; j++)


turn( );
}
}
}
BL 18 - 2

The task at hand:


Add additional code in the area of <#1> that will add the row and column
numbers and then decide if the sum is an even or an odd number. If odd,
numTurns will be set to 3 and if even, set to 5. For the decision making part of
this code, use a selection operator instead of the more traditional if.

Run main, step the bug, and observe the bug turning according to these rules.
BL 19 - 1

BugLab 19 – Two dimensional array, (Blue Pelican Java Lesson 35)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab19) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
In this lab we want the bug to turn only if both canMove is true and the cell to
which we are to move has not been visited by this bug earlier. A two-dimensional
boolean array corresponding cell by cell to the graphical grid will keep a record of
visits to each cell. To prepare for this, make the following changes to BasicBug:

import info.gridworld.actor.Bug;
import info.gridworld.grid.Location; //Necessary for Location class below
public class BasicBug extends Bug
{
public void act( )
{
//Get the row and col of the position to which we will try to move.
int rowIndex = -1;
int colIndex = -1;
Location loc = getLocation();
if(canMove( )) //Test to see if adjacent cell is valid for a move
{
loc = loc.getAdjacentLocation(getDirection());
rowIndex = loc.getRow( );
colIndex = loc.getCol( );
}

//Only move if not blocked and the cell lying ahead has not been visited
if( canMove( ) && <#1>) )
{
move( );

//Store true in the array to indicate current cell has been visited.
<#2>
BL 19 - 2

}
else
{
turn( );
}
}

//Instance field automatically initialized with false in each element.


<#3>
}

The task at hand:


First, create a two-dimensional boolean array called visitedCell in the area above
denoted by <#3>. Dimension the array to a depth of 10 for both indices. Note that
each element of a boolean array is automatically initialized with false.

Fill in code for area <#1> above so as to provide a boolean value of false if the
grid cell corresponding to visitedCell[row][col] has not yet been visited.

Finally, in code area <#2> store a true in the appropriate cell of the visitedCell
array. Thus, a true in any particular cell will indicate that the corresponding grid
cell has been visited by the bug.

Run main, step the bug, and observe the bug moving and turning according to these rules.
BL 20 - 1

BugLab 20 – Inheritance, overriding, (Blue Pelican Java Lesson 36)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab20) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
In this lab we will leave the fundamental act method intact; however, we will
override the turn method in the Bug class (inherited here via extends Bug) by
creating a new turn method with code of our own. Notice the skeleton of the turn
method in the code below where we will eventually place new code.

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
}
}

public void turn( ) //Overrides the turn method in Bug


{
<#1>
}
}

The task at hand:


In the area of <#1> above, place code that will that will report the current
direction of the bug and if greater than 180 degrees, add 45 degrees and set that as
BL 20 - 2

the new direction. Otherwise, subtract 135 degrees and set that as the new
direction.

Hint: The method getDirection returns an integer value in degrees that is the
current direction of the bug. Likewise, the setDirection method receives an int
type parameter and determines a new direction for the bug.

Run main, step the bug, and observe that the old default behavior of turning 45 degrees
clockwise has been replaced with this new behavior.
BL 21 - 1

BugLab 21 – Using instanceof (Blue Pelican Java Lesson 36)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab21) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in two classes
mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Create BasicBugRed and BasicBugBlue:


Modify the code for BasicBug and rename it BasicBugRed It should have a
default constructor that automatically sets the bug color to red (using
setcolor(Color.RED). Also notice that when unable to move forward, it turns
three times. The code for this class is as follows where you must supply the
default constructor.

import info.gridworld.actor.Bug;
import java.awt.Color;
public class BasicBugRed extends Bug
{

//Default constructor goes here.

public void act( )


{
if( canMove( ) )
{
move( );
}
else
{
turn( );
turn( );
turn( );
}
}
}

In a similar way, create a BasicBugBlue class in which the default constructor


automatically produces a blue bug.
BL 21 - 2

Create SuicideBug:
Create a SuicideBug class as shown below. Notice that the default behavior of a
simple 45 degree turn when a move is not possible has now been replaced with
more complicated code. Also notice that the default constructor automatically sets
the color to green:

import info.gridworld.actor.Bug;
import info.gridworld.grid.Location;
import info.gridworld.grid.Grid;
import info.gridworld.actor.*;
import java.awt.Color;
public class SuicideBug extends Bug
{
public SuicideBug( )
{
//Constructor automatically sets color to green
setColor(Color.GREEN);
}

public void act( )


{
if( canMove( ) )
{
move( );
}
else
{
Location locMe = getLocation( );
Location locNeighbor = locMe.getAdjacentLocation(getDirection( ));
Grid<Actor>gr = getGrid( );

if(gr.isValid(locNeighbor)) //Is this a valid cell?


{
//Get object in this cell
Actor adjacentNeighbor = gr.get(locNeighbor);

//Modifications go here

}
else
turn( );
}
}
}
BL 21 - 3

Do not be concerned with all the complicated looking code in bold. All it does is get the
object directly in front of us and store it in adjacentNeighbor.

The task at hand:


Our job here is to modify the above code (where it says Modifications go here)
so as to determine (using instanceof) if adjacentNeighbor is an object of type
BasicBugRed. If it is of type BasicBugRed, this SuicideBug eliminates itself using
the removeSelfFromGrid method (this method receives no parameters); otherwise,
a turn is executed.

Adjusting the BasicBugRunner code:


Modify (just copy and paste) the following BasicBugRunner class so as to
produce two separate bugs; a BasicBugRed object, a BasicBugBlue object,
and a SuicideBug object..

//This class will not compile until the BasicBug class first compiles.
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
public class BasicBugRunner
{
public static void main(String args[])
{
ActorWorld world = new ActorWorld( );

BasicBugRed bugR = new BasicBugRed();


BasicBugBlue bugB = new BasicBugBlue();
SuicideBug bugS = new SuicideBug();

Rock rock1 = new Rock( );


rock1.setColor(Color.BLACK);

world.add(new Location(5,3), bugS);


world.add(new Location(1,2), bugR);
world.add(new Location(2,5), bugB);

world.add(new Location(1, 4), rock1);


world.show( );
}
}

Testing the code:


Run the main method in BasicBugRunner and the resulting display should be as
follows:
BL 21 - 4

Fig. BugLab21-1 Initial position


and orientation of the three bugs
& rock. (Red bug - upper left,
green bug - bottom, and blue
bug - right)

Continue clicking the Step button until the bug positions are as shown below:

Fig. BugLab21-2 An apparent


collision between the green bug
(bottom) and the red bug (just
above the green bug).
BL 21 - 5

At this point it would seem that the green bug is about to eliminate itself because
it is unable to move and it is an object of type BaiscBugRed that is blocking its
movement. Click Step again, and to our surprise the green bug does not eliminate
itself. Why?

The reason is that when Step is clicked either the red bug’s act method or the
green bug’s act method will execute first. In this case it is the red bug that moves
first; therefore, after it moves the green bug no longer sees an obstacle.

Run the code again and advance the bugs to the state of the last picture above.
Then click on the red bug and set a new direction of 180 degrees. The red bug will
still act first; however, instead of moving, it will now turn. Then when the green
bug finally acts it will see the red bug directly in front of it and will eliminate
itself.

Continue to experiment by clicking on empty cells and creating more red and blue
bugs. Watch them interact with the green SuicideBug bug as the Step button is
clicked, and finally observe the SuicideBug object eliminate itself according to the
rules we have established.
BL 22 - 1

BugLab 22 – Exceptions (try-catch) (Blue Pelican Java Lesson 37)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab22) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBugRunner:
The new BasicBugRunner class will be exactly the solution to BugLab14 where
the properties of the bug in its initial position are written to a disk file. Recall that
the toString method provides the needed information about the bug.

import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
import java.io.*; //Necessary for FileWriter, PrintWriter, & IOException
public class BasicBugRunner
{
public static void main(String args[]) throws IOException
{
ActorWorld world = new ActorWorld( );
BasicBug bug1 = new BasicBug( );
bug1.setColor(Color.ORANGE);
Rock rock1 = new Rock( );
rock1.setColor(Color.BLACK);
world.add(new Location(5,3), bug1);
world.add(new Location(1, 3), rock1);
world.show( );

//Store initial position of the bug to a file


FileWriter fw = new FileWriter("outputFile.txt"); //Open file
PrintWriter output = new PrintWriter(fw);
output.println(bug1.toString()); //Send info to file
output.close( );
fw.close( );
}
}
BL 22 - 2

The task at hand:


In addition to the storage of the initial data for the bug, the desire is for its data to
also be stored at the conclusion of the act method in BasicBug. Recall that the act
method executes each time the Step button is clicked.

Each time we write to the file in the act method, we will need to write in the
append mode; otherwise, each new submission to the file would simply overwrite
whatever was already present in the file. To accomplish all this, place the
following code at the very bottom of the act method in the BasicBug class.

FileWriter fw = new FileWriter("outputFile.txt", true); //Open file


PrintWriter output = new PrintWriter(fw);
output.println(bug1.toString()); //Send bug1 info to file
output.close( );
fw.close( );

Notice that the FileWriter constructor is sent two arguments. The first is the file
name and the second is true which indicates the append mode.

After placing this code at the bottom of act, it will be discovered that the class
will not compile. Normally we could simply append throws IOException to the
act method signature. Upon doing this we again discover that the class won’t
compile. This is because we are overriding the act method in the inherited Bug
class, and that original method did not use throws IOException.

The only way out of this dilemma is to place the above code in a try block. The
corresponding catch statement should print the following sentence and then stop
execution of the program.

"There is a problem writing to the file."

Run main, step the bug several times, and display(using Note Pad or Word Pad) the text
file that is produced. The results should be similar to the following:

BasicBug[location=(5, 3),direction=0,color=java.awt.Color[r=255,g=200,b=0]]
BasicBug[location=(4, 3),direction=0,color=java.awt.Color[r=255,g=200,b=0]]
BasicBug[location=(3, 3),direction=0,color=java.awt.Color[r=255,g=200,b=0]]
BasicBug[location=(2, 3),direction=0,color=java.awt.Color[r=255,g=200,b=0]]
BasicBug[location=(2, 3),direction=45,color=java.awt.Color[r=255,g=200,b=0]]
BasicBug[location=(1, 4),direction=45,color=java.awt.Color[r=255,g=200,b=0]]
BasicBug[location=(0, 5),direction=45,color=java.awt.Color[r=255,g=200,b=0]]
BL 23 - 1

BugLab 23 – Using recursion (Blue Pelican Java Lesson 40)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab23) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBug:
The following code for BasicBug produces it’s default behavior; the bug moves
when it can and when it can’t, it turns 45 degrees clockwise.

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
}
}
}

The task at hand:


We wish to modify the code above so that act is recursively called so as to
continually move the bug forward. Recursion should stop when the bug needs to
turn. As a result, each time the Step button is clicked, the bug should be seen to
move forward as far as it can (until a turn is necessary). It will then stop and wait
for the next click of the Step button.

While recursion is one of the more sophisticated concepts in computer science, this
particular lab is one of the easiest. Actually, only one line of code needs to be added to
make the bug perform as described.
BL 24 - 1

BugLab 24 – Using ArrayList (Blue Pelican Java Lesson 42, 43)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab24) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBugRunner:
The following code for BasicBugRunner creates a rock and three BasicBug
objects. This will give a variety of objects to occupy an ArrayList that will be
created in the BasicBug class.

//This class will not compile until the BasicBug class first compiles.
import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
public class BasicBugRunner
{
public static void main(String args[])
{
ActorWorld world = new ActorWorld( );
BasicBug bug1 = new BasicBug( );
bug1.setColor(Color.ORANGE);

BasicBug bug2 = new BasicBug( );


bug2.setColor(Color.GREEN);

BasicBug bug3 = new BasicBug( );


bug3.setColor(Color.RED);

Rock rock1 = new Rock( );


rock1.setColor(Color.BLACK);

world.add(new Location(5,3), bug1);


world.add(new Location(2,7), bug2);
world.add(new Location(4,6), bug3);
BL 24 - 2

world.add(new Location(1, 3), rock1);


world.show( );
}
}

The task at hand:


Our job here is to modify BasicBug as follows and then produce any ArrayList
object containing the Location objects associated with all of the objects in the grid
(rocks, bugs, and flowers):

import info.gridworld.actor.Bug;

//All these imports necessary for the bottom block of code


import info.gridworld.grid.*;
import java.util.*;
import info.gridworld.actor.Actor;
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
}

//Print the coordinates of all occupied cells.


Grid<Actor> gr = getGrid( ); //Obtain the grid object
//Produce an ArrayList object containing Location objects
// identifying each occupied cell.
ArrayList<Location> = ???;
for( …cycle through each object in the ArrayList…)
{
…Print the row and column number of each occupied cell…
}
System.out.println( ); //Print a blank line
}
}

To produce the ArrayList object, use the grid object’s getOccupiedLocations


method (it receives no parameters). Obtain the row and column integer values for
BL 24 - 3

each Location object using Loaction’s getRow and getCol methods. Then print
these two values

Testing the code:


Run main in BasicBugRunner, advance the bugs by clicking the Step button
several times, and observe the printout on the console screen. It should be
recognized that the act method we have modified executes for each bug each
time the Step button is clicked. As the bugs advance they leave behind a trail of
Flower objects. Thus, the number of objects on the grid increases with each click
of the Step button. Following is a typical printout after several steps.

1, 3
1, 7
2, 7
4, 6
5, 3

1, 3
1, 7
2, 7
3, 6
4, 6
5, 3

1, 3
1, 7
2, 7
3, 6
4, 3
4, 6
5, 3

0, 7
1, 3
1, 7
2, 7
3, 6
4, 3
4, 6
5, 3
BL 25 - 1

BugLab 25 – ArrayList and ListIterator


(Blue Pelican Java Lesson 43 & 44)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab25) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBugRunner:
This lab is very similar to BugLab24. Use the exact same BasicBugRunner class
as in that lab. It creates three bugs and one rock.

The task at hand::


In BugLab24 we had the following code for the BasicBug class. Modify the
portion in bold using a ListIterator to access each Location object in the list and
then prints its row and column numbers as before:

import info.gridworld.actor.Bug;
//The following imports necessary for bottom block of code
import info.gridworld.grid.*;
import java.util.*;
import info.gridworld.actor.Actor;
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
}
//Print the coordinates of all occupied cells.
Grid<Actor> gr = getGrid( ); //Obtain the grid object
//locList is an ArrayList of all the occupied locations.
ArrayList<Location> locList = gr.getOccupiedLocations( );
BL 25 - 2

for(int j = 0; j < locList.size( ); j++)


{
Location loc = locList.get(j);
//Print the row and column of an occupied cell.
System.out.println(loc.getRow( ) + ", " + loc.getCol( ));
}
System.out.println( ); //Print a blank line
}
}

Testing the code:


Run main in BasicBugRunner, advance the bugs by clicking the Step button
several times, and observe the printout on the console screen. It should be
recognized that the act method we have modified executes for each bug, each
time the Step button is clicked. As the bugs advance they leave behind a trail of
Flower objects. Thus, the number of objects on the grid increases with each click
of the Step button. Following is a typical printout after several movements.
1, 3
1, 7
2, 7
4, 6
5, 3

1, 3
1, 7
2, 7
3, 6
4, 6
5, 3

1, 3
1, 7
2, 7
3, 6
4, 3
4, 6
5, 3

0, 7
1, 3
1, 7
2, 7
3, 6
4, 3
4, 6
5, 3
BL 26 - 1

BugLab 26 – Sorting and compareTo


(Blue Pelican Java Lessons 41 & 45)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab26) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBugRunner:
This lab is very similar to BugLab24. Use the exact same BasicBugRunner class
as in that lab. It creates three bugs and one rock.

The task at hand:


In BugLab24 we had the following code for the BasicBug class, the only
difference being instead of printing the row and column indices of the occupied
cells, we now put them in a String array that will ultimately be sorted.

import info.gridworld.actor.Bug;
//All these imports necessary for bottom block of code
import info.gridworld.grid.*;
import java.util.*;
import info.gridworld.actor.Actor;
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
}
String locStr[] = getLocationArray( );

//Modifications go here
}
BL 26 - 2

//This method produces a String array in "c,r" format of the coordinates


//of all occupied cells.
public String[] getLocationArray( )
{
//Get the coordinates of all occupied cells.
Grid<Actor> gr = getGrid( ); //Obtain the grid object
//locList is an ArrayList of all the occupied locations.
ArrayList<Location> locList = gr.getOccupiedLocations( );
String locStr[] = new String[locList.size( )];
for(int j = 0; j < locList.size( ); j++)
{
Location loc = locList.get(j);
//Stuff a String array with column & row numbers separated by a comma.
locStr[j] = "" + loc.getCol( ) + "," + loc.getRow( );
}
return locStr;
}
}

It is not necessary to understand the getLocationArray method (just copy and


paste): all that is necessary is to know that it returns a String array containing the
coordinates of occupied cells.

Notice that the elements of String array locStr typically look something like “3,5”
where the first number is the column and the second is the row of an occupied
cell. The purpose of this lab is to sort by column (the primary sort key) with the
row number as a secondary key.

The reason that String locStr array is not built with the more customary order of
the row-first and column-second, is because the coordinates produced by
getLocationArray already is naturally ordered with respect to rows. Therefore, it
would not be a meaningful exercise to sort an array that is already ordered.

In the “Modification go here” code area above, insert the following code:

printStringArray(locStr); //Print the unordered array.


sort(locStr); //Sort the array in ascending order.
printStringArray(locStr); //Print the ordered array.
System .out.println(“******************”); //Separator

Clearly, there is a need to produce two methods here: printStringArray and sort
where each receives the String array, locStr. Create a sort method that orders the
array in ascending order. Use one of the sort methods from Lesson 41 (Bubble
Sort is the simplest) and make use of the compareTo method.
BL 26 - 3

The following partial output of the printStringArray method is produced at end


of the first execution of the act method (notice the second group is ordered):

3,1
7,1
7,2
6,4
3,5

3,1
3,5
6,4
7,1
7,2

******************

Testing the code:


Run main in BasicBugRunner, advance the bugs by clicking the Step button
several times, and observe the printout on the console screen. It should be
recognized that the act method executes for each bug each time the Step button is
clicked. As the bugs advance they leave behind a trail of Flower objects. Thus,
the number of objects on the grid increases with each click of the Step button.

Observe that the printout occurs in pairs with the first unordered, the second
ordered, and then a row of asterisks serving as a separator between the pairs.
BL 27 - 1

BugLab 27 – Sorting, using StringBuffer’s reverse method,


(Blue Pelican Java Lesson 31, 41)

(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab27) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBugRunner:
This lab is very similar to BugLab26. Use the exact same BasicBugRunner class
as in that lab. It creates three bugs and one rock.

The task at hand:


In BugLab26 we had the following code for the BasicBug class: it’s the same here
except for some modifications in the printStringArray method. The sort and
printStringArray methods were assigned in that lab. If that lab has been
completed, your instructor might want to give you the code for those two
methods.

import info.gridworld.actor.Bug;
//All these imports are necessary for the getLocationArray method.
import info.gridworld.grid.*;
import java.util.*;
import info.gridworld.actor.Actor;
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
}
String locStr[] = getLocationArray( );
BL 27 - 2

printStringArray(locStr); //Print the unordered array.


sort(locStr); //Sort the array in ascending order.
printStringArray(locStr); //Print the ordered array
System.out.println("******************"); //Separator
}

//This method produces a String array in "c,r" format of the coordinates


//of all occupied cells.
public String[] getLocationArray( )
{
//Get the coordinates of all occupied cells.
Grid<Actor> gr = getGrid( ); //Obtain the grid object
//locList is an ArrayList of all the occupied locations.
ArrayList<Location> locList = gr.getOccupiedLocations( );
String locStr[] = new String[locList.size( )];
for(int j = 0; j < locList.size( ); j++)
{
Location loc = locList.get(j);
//Stuff a String array with column & row numbers separated by
//a comma.
locStr[j] = "" + loc.getCol( ) + "," + loc.getRow( );
}
return locStr;
}

public void sort(String s[]) //Bubble Sort


{
//Your instructor may want to provide this code since it was part of
//a previous lab (BugLab26)
}

//Print the array


public void printStringArray(String s[])
{
//Your instructor may want to provide this code since it was part of
//a previous lab (BugLab26)

}
}

Again, it is not necessary to understand the getLocationArray method (just copy


and paste): all that is necessary is to know that it returns a String array containing
the coordinates of occupied cells.

The purpose of this lab is to reverse the elements of the locStr array just before
printing so as to produce a more standard “row, column” sequence instead of the
BL 27 - 3

present “column, row” sequence. For example, if an element of the locStr array is
“3,7”, we want, instead, to print “7,3”. Use the reverse method of StringBuffer
to accomplish this.

Recall from BugLab26 that the reason that String locStr array was not originally
built with the more customary order of the row-first and column-second, is
because the coordinates produced by getLocationArray already is naturally
ordered with respect to rows. Therefore, it would not be a meaningful exercise to
sort an array that is already ordered.

The following partial output of the modified printStringArray method is


produced at end of the first execution of the act method. Notice the second group
is ordered with respect to the column number (the trailing coordinate):

1,3
1,7
2,7
4,6
5,3

1,3
5,3
4,6
1,7
2,7

******************

Testing the code:


Run main in BasicBugRunner, advance the bugs by clicking the Step button
several times, and observe the printout on the console screen. It should be
recognized that the act method executes for each bug each time the Step button is
clicked. As the bugs advance they leave behind a trail of Flower objects. Thus,
the number of objects on the grid increases with each click of the Step button.

Observe that the printout occurs in pairs with the first unordered, the second
ordered, and then a row of asterisks serving as a separator between the pairs.
BL 28 - 1

BugLab 28– Sorting with Comparator (Blue Pelican Java Lesson 45)
(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab28) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBugRunner:
This lab is very similar to BugLabs 24-27. Use the exact same BasicBugRunner
class as in those labs. It creates three bugs and one rock.

Modify BasicBug:
The BasicBug class will have the following code. Notice the area of
“Modifications go here.” That is where a Comparator object will be used to
sort the locStr array:

import info.gridworld.actor.Bug;
//All these imports are necessary for the getLocationArray method
import info.gridworld.grid.*;
import java.util.*;
import info.gridworld.actor.Actor;
public class BasicBug extends Bug
{
public void act( )
{
if(canMove( ))
{
move( );
}
else
{
turn( );
}
String locStr[] = getLocationArray( );

//Sort using a comparator

….Modifications go here….
BL 28 - 2

//Print the sorted array


for(int j = 0; j < locStr.length; j++)
{
System.out.println(locStr[j]);
}
System.out.println( ); //Print a blank line.
}

//This method produces a String array in "r,c" format of the


//coordinatesof all occupied cells.
public String[] getLocationArray( )
{
//Get the coordinates of all occupied cells.
Grid<Actor> gr = getGrid( ); //Obtain the grid object
//locList is an ArrayList of all the occupied locations.
ArrayList<Location> locList = gr.getOccupiedLocations( );
String locStr[] = new String[locList.size( )];
for(int j = 0; j < locList.size( ); j++)
{
Location loc = locList.get(j);
//Stuff a String array with row & col numbers separated
//by a comma.
locStr[j] = "" + loc.getRow( ) + "," + loc.getCol( );
}
return locStr;
}
}

Again, it is not necessary to understand the getLocationArray method (just copy


and paste): all that is necessary is to know that it returns a String array containing
the coordinates of occupied cells. Unlike several previous labs, notice that the
String array returned by getLocationArray is in standard row-column form.

The task at hand:


Create a class that implements Comparator and then implement the compare
method inside it. The two Objects it receives will be Strings in the form “3,5”.
Convert these numbers into a product (15 in this example) and compare those
products inside the compare method.

Use the class thus produced to create a Comparator object and this pass that
object along with the String array, locStr, to the Arrays.sort method. Place this
code in the code area, “Modifications go here.”

Testing the code:


Run main in BasicBugRunner, advance the bugs by clicking the Step button
BL 28 - 3

several times, and observe the printout on the console screen. It should be
recognized that the act method executes for each bug each time the Step button is
clicked. As the bugs advance they leave behind a trail of Flower objects. Thus,
the number of objects on the grid increases with each click of the Step button.

The following output is produced with a single click of the Step button. Notice the
order is with respect to the product of the row and column numbers.

1,3
1,7
2,7
5,3
4,6

1,3
1,7
2,7
5,3
3,6
4,6

1,3
1,7
4,3
2,7
5,3
3,6
4,6
BL 29 - 1

BugLab 29 – Set intersection, (Blue Pelican Java Lesson 46)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab29) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

The BasicBug class:


Leave the BasicBug class empty (just as it is when imported). This is not a
problem since it inherits the Bug class where the default behavior of a bug is
determined by the act method. Briefly, that behavior is to move when not blocked;
otherwise, turn 45 degrees clockwise.

import info.gridworld.actor.Bug;
public class BasicBug extends Bug
{
//No code
}

Modify BasicBugRunner:
The BasicBugRunner class generates 30 BasicBug objects of random color that
are then randomly placed within the 10 X 10 grid. This fundamental code is
presented below and can be simply copied and pasted into an IDE. Notice the
sections marked with <#1>, <#2>, <#3>, and <#4> are areas where code is to
added.

import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
import java.util.*;
public class BasicBugRunner
{
public static void main(String args[])
{
ActorWorld world = new ActorWorld( );
<#1>
BL 29 - 2

int totalBugs = 30;


BasicBug bug[] = new BasicBug[totalBugs];
boolean cell[][] = new boolean[10][10];
Random rnd = new Random( );

int count = 0 ;
while(count < totalBugs)
{
//Randomlly select row and column indices
int rowIndx = rnd.nextInt(10);
int colIndx = rnd.nextInt(10);

//Ensure that the cell is empty before adding bug


if(cell[rowIndx][colIndx]==false)
{
bug[count] = new BasicBug( );

//Randomlly set a color


int clrIndx = rnd.nextInt(4);
switch(clrIndx)
{
case 0:
bug[count].setColor(Color.RED);
<#2>
break;
case 1:
bug[count].setColor(Color.GREEN);
break;
case 2:
bug[count].setColor(Color.BLUE);
break;
case 3:
bug[count].setColor(Color.MAGENTA);
break;
}
world.add(new Location(rowIndx,colIndx), bug[count]);
cell[rowIndx][colIndx] = true; //Mark the cell as occupied
<#3>

count++;
}
}
world.show( );
<#4>
}
}
BL 29 - 3

The task at hand:


The goal here is to eliminate from the grid any bugs that are both red and on the
left side of grid (columns 0 through 4). A requirement like this might be imposed
to set up the initial board of a game.

This is to be accomplished by storing all red bug objects in Set set1 and all bug
objects residing on the left side of the grid in Set set2. Find the intersection of
these two Sets and then remove from the grid all of the bug objects residing in this
intersection Set.

<#1> In this code area, instantiate two HashSet objects called redSet and leftSet
using BasicBug as a type parameter.

<#2> In this code area, add the current bug object ( bug[count] ) to Set redBug.

<#3> In this code area, add the current bug to Set leftBug only if the bug is in the
left portion of the grid ( colIndx < 5 ).

<#4> In this code area, produce a Set that is the intersection of redSet and leftSet.
Iterate through that Set and remove all its elements from the grid using the
removeSelfFromGrid method.

Testing the code:


Run main in BasicBugRunner. When the grid appears, there should be no red
bugs on the left side. Repeat and see a different placement since the positions and
colors are randomly generated.
BL 30 - 1

BugLab 30 – Map, (Blue Pelican Java Lesson 47)


(Teacher: Refer to Labs 4 and earlier for a detailed discussion of the various GridWorld
methods used in these labs (act, canMove, move, & turn). If the students have done the
previous labs, then they should already be accustomed to the use of these methods.)

Create the project:


Create a new project (named BugLab30) with your IDE and into the resulting
folder, import the two classes in the BasicBug folder. In the IDE BlueJ, it’s done
as follows:
Create the project with Project | New project, being careful to create this
project within the C:\GridworldProjects folder. Then bring in the two
classes mentioned above with Project | Import (Navigate to the
C:\GridWorldProjects\BasicBug folder and then click Import.)

Modify BasicBugRunner:
The BasicBugRunner class generates 10 BasicBug objects of random color that
are then randomly placed within the 10 X 10 grid. This is the initial state of the
board for a game. This fundamental code is presented below and can be simply
copied and pasted into an IDE.

Take special note of the line of code designated with the rem, “//Create bug”.
Notice that we are sending the BasicBug constructor a String that names the bug
objects with names like “bug1”, “bug2”, etc. Thus, it will be necessary to have an
appropriate constructor in BasicBug to receive this String and then assign that
name to a state variable.

import info.gridworld.actor.ActorWorld;
import info.gridworld.grid.Location;
import java.awt.Color;
import info.gridworld.actor.Rock;
import java.util.*;
public class BasicBugRunner
{
public static void main(String args[])
{
ActorWorld world = new ActorWorld( );

int totalBugs = 10;


BasicBug bug[] = new BasicBug[totalBugs];
boolean cell[][] = new boolean[10][10];
Random rnd = new Random( );

int count = 0 ;
while(count < totalBugs)
{
BL 30 - 2

//Randomlly select row and column indices.


int rowIndx = rnd.nextInt(10);
int colIndx = rnd.nextInt(10);

//Ensure that the cell is empty before adding bug


if(cell[rowIndx][colIndx]==false)
{
bug[count] = new BasicBug(“bug”+count);//Create bug

//Randomlly set a color.


int clrIndx = rnd.nextInt(4);
switch(clrIndx)
{
case 0:
bug[count].setColor(Color.RED);
break;
case 1:
bug[count].setColor(Color.GREEN);
break;
case 2:
bug[count].setColor(Color.BLUE);
break;
case 3:
bug[count].setColor(Color.MAGENTA);
break;
}
world.add(new Location(rowIndx,colIndx), bug[count]);
cell[rowIndx][colIndx] = true; //Mark the cell as occupied

count++;
}
}
world.show( );
}
}

The BasicBug class:


Modify the BasicBug class as follows and notice the areas designated with <#1>,
<#2>, and <#3> where more code is to be entered.

import info.gridworld.actor.Bug;
import java.util.*;
public class BasicBug extends Bug
{
public BasicBug(String nm)
{
BL 30 - 3

bugName = nm;
<#2>
}

public void act( )


{
if(canMove( ))
{
move( );
}
else
{
turn( );
<#3>
}
System.out.println(dirMap);
}

public String bugName;


<#1>
}

The task at hand:


Suppose that you are a member of a programming team that produces games and
the head software engineer has come to you with a problem. She is concerned
about how to detect errors in the program and needs you to develop some code
that will help analyze the state of the game board at any time.

The requirement is to create a static Map object in which the keys are to be the
bug names (name data member) while the values are to be the respective
directions of the bugs.

<#1> In this code area, instantiate a static TreeMap object called dirMap.
Instantiate this object using type parameters. The key will be a String and the
value will be an Integer. Notice that by making this Map object static, this same
object is used by all of the bug objects.)

<#2> In this code area (the constructor), add to dirMap the pair nm and an integer
direction of 0 since the initial direction of the bug is 0 degrees - north. Use the put
method to insert this pair into the Map

<#3> In this code area (just after a turn), update dirMap with the current key-
value pair. Recall that the bug’s name data member is the key and its new
direction is the value. Use the getDirection method of the bug object to obtain its
new direction.
BL 30 - 4

Testing the code:


Run main in BasicBugRunner, click the Step button and observe the printout in
the console window. Realize that for the current placement of the println
statement, that a new line is printed each time act is called for each bug. Since act
is called for each bug each time the Step button is clicked, there will be 10 printed
lines (there are 10 bugs) after each click. Below is a sample of the expected
printout after just one click:

{bug0=0, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}
{bug0=45, bug1=0, bug2=0, bug3=0, bug4=0, bug5=45, bug6=0, bug7=0, bug8=0, bug9=0}

Notice that some of the bugs have already had to turn after just a single step. Now
move the println statement to just after turn( ) and observe that the Map is only
printed when a turn is executed.

As more code is added BasicBug to implement the game, the Map could be
printed at any place in the code in order to help analyze errors.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy