CS 1110 - Spring 2015 - Previous Lab Projects

Lab 12 & 13 - April 9 & 16 - Project Work

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Project Work

We are giving you these two weeks of lab to specifically work on your game project. Take advantage of it! There is nothing to submit this week.

Lab 11 - April 2 - Typing Game

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Super Important Pairing!

Today you will pick your partner that you will be doing your game project with. Whoever your partner is at the end of lab today will be your partner for the next three weeks! We encourage you to partner with someone new, but it is not required. Anyone not paired by the end of lab will be assigned a partner. No exceptions!

Enter your partner for both Lab 11 and Project 2 on the lab and project submission page.

Activity 3: Starting Out

You’ll need a couple files to get started. Create a new project called “Typing Game” and copy the following two files into it:

Before editing files, it is always a good ideas to review what you have to start with.

  1. Try running TypingGame as is. What does it display? What happens if you press a key while the TypingGame window is focussed?
  2. Open TypingGame.java and read through the comments.
  3. Try changing what TypingGame does. For example, can you make it display a Z in the bottom right part of the screen? Can you make it print Hooray! whenever you type T?
  4. Open Letter.java and read through the methods and comments there. Is there any method that looks incomplete or does not make sense? How would you draw a Letter object in the TypingGame screen?

Activity 4: The Typing Game

TypingGame

The game you will be working on today is a simple typing game in which:

  • Random letters appear on the screen at random locations
  • The letter stays there until it has been typed
  • When it has been typed, it’s removed from the screen and the score goes up by 1

That’s it!

The game as it is now doesn’t do most of that. We have left comments in the code as to what you need to work on, but more information can be found below.

Activity 5: Letter Constructor

The first thing to do is finish the Letter class. The Letter class contains the char of the letter and the x and y coordinates it will appear on screen, along with some helper methods for printing, etc. Take a look at the code to get a feel for it.

In the constructor, you should write code that picks a random letter from a String that is passed to the constructor that contains an alphabet and then also assigns the x and y coordinates.

For instance, if the user called:

Letter letter = new Letter("abcd", 30, 30);

A new Letter will be created that will display at (30,30) with one of the characters a, b, c, or d.

Houw would you test if your Letter class works, without finishing the game? Adding a testing class with a main method might be a good idea.

Activity 6: TypingGame.java

In the TypingGame.java file, you will find some // TODO comments that indicate where you need to add code. You’ll need to:

  • add some fields
  • instantiate them in the constructor
  • handle what happens with the user presses a key - check to see if the key pressed is in the ArrayList letters and if it is, remove the letter and increase the score by 1
  • create a new Letter and add it to the ArrayList letters every few seconds
  • draw the letters found in the ArrayList letters to the screen on each refresh

Hint: We have provided some helper code to check to see if a char is equivalent to a key press. Consider something that might look like this:

1
2
3
4
Letter let = new Letter('A', 100, 100);
if(let.equals(event.getKeyChar())) {
  ...
}

Activity 7: Submission

Submit to the lab submission page your Letter.java and TypingGame.java files.

Lab 10 - March 26 - Broken Flappy Bird

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Pairing

Time to find a new partner! You’ll be starting a new project in the coming weeks, so take time at the beginning of lab to find someone new to work with! (It’s okay to work with the same person, but we’d really like you branch out.)

Activity 3: Starting Out

First, have you played Flappy Bird before? If not, take a couple minutes and go try it out! Flappy Bird Online

We have another project for you to import.

Download this zip file: BrokenFlappyBird.zip

  • In Eclipse, click File > Import.
  • Then choose General > Existing Project into Workspace
  • Press the “Select archive file” button, then select the zip file and it should create a new project for you with the code you start with!

Activity 4: The Starting Code

There are five .java files in the project:

  • FlappyBird.java - this is where main() is and controls the basic game logic
  • Bird.java - represents the Flappy Bird; has information about it’s position and methods for making it move
  • Pipe.java - represents both the top and bottom parts of the pipe obstacles; contains two rectangles - one for the top pipe and one for the bottom
  • Ground.java - represents the ground and lets the game know to exit if the bird touches the ground
  • GameBoard.java - handles many of the drawing functions; you do not need to look at or edit this file

flappy bird

Activity 5: It’s broken!

So, Prof. Sherriff did a terrible job programming Flappy Bird… there are bugs left in his code! It’s up to you to find them.

First, create a new file in Eclipse called Errors.txt; use the File → New → File option instead of File → New → Class, and give it the name Errors.txt (exactly, capitalization matters). As you find errors, write down exactly where you found them and how you fix them.

There are different types of errors that Prof. Sherriff made. Some errors are compile errors, keeping the code from even running. First, you’ll need to fix these. There are 2 of them, and Eclipse will help you find them.

Next, there are runtime errors. These errors make the code throw an exception at some point. There are two of these as well. See if you can follow the calls in the stack trace (you know, the red text you see in the Eclipse console when the program crashes) to figure out where these two problems are.

There are also requirements or logic errors. These are errors in which the game “works”, but doesn’t work the way it should.

Specifically:

  • The bird is supposed to “flap” when you click the screen… but it doesn’t… that’s not good!
  • The gravity here seems a bit… off. Perhaps we should tone it down a bit?
  • Something doesn’t seem quite right with running into the pipes…

Find these errors and write down exactly where you found them and how you fixed them.

Activity 6: Submission

Submit to the lab submission page a text document named Errors.txt containing the information you wrote down regarding the location of the errors and how you fixed them.

Lab 9 - March 19 - Email Hunt Working Lab

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Reminder about Cheating

It is cheating to copy code from the internet, a friend, or any other source besides the course material (lectures or textbook) or a TA. Many people have been copying something called a RegEx, RegExp, Regular Expression, or Pattern (which generally provides little or no benefit over just using String methods). These are code, and copying them is cheating. If you have submitted code with these kinds of constructs which you did not create yourself, get rid of them and resubmit.

Activity 3: Work on Email Hunt with your partner

Due to the issues with the snow and with some partner confusions, we will give you lab this week to work on Email Hunt. If you come to lab and you have not started on the project, or are not far at all, the TAs will NOT spend a lot of time with you! You need to put in time before you come to lab to work on this project!

No submission is required this week.

Students who have completed the project should show up to lab to register attendance and may leave after showing their completed project to the TAs.

Lab 8 - March 5 - Word Scramble

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

You should work with your partner for the first partner project, Email Hunt. You should plan to work with this partner for the next few weeks until the project is complete. When you are done with this lab assignment, spend the rest of the time working on your project.

Activity 3: Starting Out

The goal of the lab today is to do word replacement in a body of text. We will provide you with a list of nouns, a list of verbs, and a list of adjectives. Your job is to write a program that reads in a body of text and whenever it finds a word that is in one of the three lists, it replaces it with another random word from that list. So, you might have some text that says:

“Bob ate a hamburger at the mall today.”

Which gets turned into:

“Bob kicked a goat at the school today.”

Create a new project called Word Scramble. Then make a new Java file called WordScramble.java.

Activity 4: Reading the Word Lists

The key to this assignment will be reading in three lists of words - one each for verbs, nouns, and adjectives. You should download these files and place them in your project directory (but not in src; one directory higher than that):

After you download the files to the right location, you can select the project in the project explorer pane of Eclipse and use F5 to ask it to refresh the project; you should then see the three text files listed.

Each list has one word per line. To make it as easy as possible to check each list for a given word, we should use an ArrayList<String> since it has a method called .contains(String word) that we can use to quickly check. If the word appears, the method returns true; otherwise it returns false.

So, create one new ArrayList<String> for each list: verbs, nouns, and adjs.

To read the lists into the ArrayLists we could write the same exact code three times, but just change the variable names and file names. But there’s a better way! We can write our own method!

Here’s what the header should look like:

public static ArrayList<String> readWordList(String filename) throws Exception

Note that:

  • public because we want the method to be visible
  • static because we want to call it without creating an instance of the class
  • ArrayList<String> because that’s what this method will create and return - an ArrayList containing all the words in one file
  • readWordList because you should always name your methods so you know what they do
  • String filename because this is the “difference” between each execution of the method - which file to read
  • throws Exception because this method will read a File and we have to handle that - we also have to put this on main

Inside of this method, write code that will open the file with that particular filename, loop through the file, adding the word on each line to an ArrayList you create inside the method. Then at the end, you return that ArrayList.

Activity 5: Replacing Words in the Books

Back in main, you should declare three ArrayList<String> objects - one each for verbs, nouns, and adjs - and call readWordList() with each file. Now you have three ArrayLists ready to go!

Now you need to open one of the files found here: https://cs1110.cs.virginia.edu/code/wordscramble/. There are several options from famous works of literature, but feel free to find your own if you want!

When reading this literature file, you should read it one word at a time. In other words, you will be using .hasNext() and .next() instead of .hasNextLine() and .nextLine(). We are going to ignore punctuation.

For each word you read with .next(), use the .contains() method with each ArrayList to see if the word appears (NOTE: all the words in the list are lowercase! You will need to handle this!). If the word DOES appear, select a random word from that list to replace it with. (HINT: if you have a Random object, consider using something like verbs.get(rand.nextInt(verbs.size()))) If the word DOES NOT APPEAR in any of the three lists, just print it to the screen.

For all of these, use .print() instead of .println().

Activity 6: Try Different Books

Try a bunch of different files! See what random things happen!

When you are done, submit and start working on your email hunt project!

Submission

We’ll continue to use the lab submission page for this lab. Only one partner needs to submit; the system will keep track of partners for you.

You must submit on time! Even if you don’t finish, submit what you have.

Lab 7 - February 26 - This Little Piggy Played Dice

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

Also, this week you should find someone to work with for the first partner project, Email Hunt. You should plan to work with this partner for the next few weeks until the project is complete.

Activity 3: Starting Out

New project time. Create a new project for this lab and make a new file called Pig.java.

This week, we’ll be writing the dice game “Pig”. If you are not familiar with the game, read up on the rules here: Pig - Dice Game Rules (We are playing the main game type, not one of the variants listed.)

Activity 4: Pseudocode

Here’s an outline of what the program will look like. This isn’t necessarily the only way to do it, but it’s one way to pull it off.

Read through this algorithm and see if you have any questions.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Program Setup (Scanner, variables you'll need, a Random number generator, etc.)

while(neither player has reached the needed score to win) {
  
  Print the current score of both players

  if(it is player 1's turn) {
      Does player 1 want to roll the die?  

      while(yes) {
          roll the die
          if(the die comes up with a 1) {
              the player loses any currently allocated points
              their turn is over (i.e. end the while loop)
          } else {
              add the die roll to a temporary set of accumulated points
              ask if they want to roll again (if yes, go to top of player 1 loop; if no, end the loop)
          }
      {
      if(player 1's last roll wasn't a 1) {
          add the temporary set of points to the player's bank
      }
      switch to player 2's turn
      
  } else {  
      // Player 2's code goes here... consider that their turn will look the same as Player 1 and fill in the code you need 
      
  }
}

Activity 5: Example Run

Here’s an example game where the score to reach is 20 (we use 20 here instead of 100 because playing to 100 takes a bit too much space… the game is the same). Your outputs do not have to exactly match ours, but this gives an idea of what the game could look like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
Welcome to Pig!

The current score is: Player 1 = 0 vs. Player 2 = 0

It's Player 1's Turn!
Rolling the die...  Player 1 rolled a 2
Adding 2 to your temp total : 0 -> 2
Do you wish to continue? (y or n): y
Rolling the die...  Player 1 rolled a 2
Adding 2 to your temp total : 2 -> 4
Do you wish to continue? (y or n): y
Rolling the die...  Player 1 rolled a 3
Adding 3 to your temp total : 4 -> 7
Do you wish to continue? (y or n): n
Player 1 is banking 7 points: 0 -> 7

The current score is: Player 1 = 7 vs. Player 2 = 0

It's Player 2's Turn!
Rolling the die...  Player 2 rolled a 6
Adding 6 to your temp total : 0 -> 6
Do you wish to continue? (y or n): y
Rolling the die...  Player 2 rolled a 1
Your turn is over!  You lost 6 points!
You currently have 0 points banked.

The current score is: Player 1 = 7 vs. Player 2 = 0

It's Player 1's Turn!
Rolling the die...  Player 1 rolled a 1
Your turn is over!  You lost 0 points!
You currently have 7 points banked.

The current score is: Player 1 = 7 vs. Player 2 = 0

It's Player 2's Turn!
Rolling the die...  Player 2 rolled a 2
Adding 2 to your temp total : 0 -> 2
Do you wish to continue? (y or n): y
Rolling the die...  Player 2 rolled a 1
Your turn is over!  You lost 2 points!
You currently have 0 points banked.

The current score is: Player 1 = 7 vs. Player 2 = 0

It's Player 1's Turn!
Rolling the die...  Player 1 rolled a 2
Adding 2 to your temp total : 0 -> 2
Do you wish to continue? (y or n): y
Rolling the die...  Player 1 rolled a 4
Adding 4 to your temp total : 2 -> 6
Do you wish to continue? (y or n): n
Player 1 is banking 6 points: 7 -> 13

The current score is: Player 1 = 13 vs. Player 2 = 0

It's Player 2's Turn!
Rolling the die...  Player 2 rolled a 3
Adding 3 to your temp total : 0 -> 3
Do you wish to continue? (y or n): y
Rolling the die...  Player 2 rolled a 4
Adding 4 to your temp total : 3 -> 7
Do you wish to continue? (y or n): y
Rolling the die...  Player 2 rolled a 5
Adding 5 to your temp total : 7 -> 12
Do you wish to continue? (y or n): n
Player 2 is banking 12 points: 0 -> 12

The current score is: Player 1 = 13 vs. Player 2 = 12

It's Player 1's Turn!
Rolling the die...  Player 1 rolled a 2
Adding 2 to your temp total : 0 -> 2
Do you wish to continue? (y or n): y
Rolling the die...  Player 1 rolled a 3
Adding 3 to your temp total : 2 -> 5
Do you wish to continue? (y or n): y
Rolling the die...  Player 1 rolled a 6
Adding 6 to your temp total : 5 -> 11
Do you wish to continue? (y or n): y
Rolling the die...  Player 1 rolled a 6
Adding 6 to your temp total : 11 -> 17
Do you wish to continue? (y or n): n
Player 1 is banking 17 points: 13 -> 30
Congrats! Player 1 wins!

Activity 6: Get Coding!

You have the pseudocode, you have an example, now get to it!

Submission

We’ll continue to use the lab submission page for this lab. Only one partner needs to submit; the system will keep track of partners for you.

You must submit on time! Even if you don’t finish, submit what you have.

Lab 6 - February 19 - Wendy’s

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

Try to find a new lab partner for this week! Meet new people! See previous lab sessions for a description of pair programming if necessary.

Activity 3: Starting Out

New project time. Create a new .java file called Wendys.java. Also download wendys.csv and put it into your project directory (not in src!).

Activity 4: Dialog Windows

We are again going to use dialog windows. Here’s a quick refresher:

We’ll use a simpler InputDialog pop up (where the user types in a String). You can use the following code:

InputDialog
1
String returnText = (String) JOptionPane.showInputDialog(message);

where message is whatever you are asking from the user.

Activity 5: Finding Your Location

Our goal for this lab is to write a program that will find the closest Wendy’s location to a given set of GPS coordinates (like you were using a GPS unit in your car). Then we want to open Google Maps to show where that Wendy’s is.

You are going to need some locations to test with. So go put some addresses you know in the tool here: http://www.gps-coordinates.net/

To start you out, the GPS coordinates for Rice Hall are: (38.0317274,-78.5110432).

Write down your test coordinates. You don’t need EVERY decimal place of precision…

Activity 6: User Input

First, you need to setup your program to ask for the user to input their GPS coordinates.

Let’s use the popup dialogs again, like shown above. The trick here is that you are reading a double not a String. So we need to do some more processing to get it to work right.

Try using something like this to process the user’s input into a double that you can use:

Popup to read a double
1
double lat = Double.parseDouble((String)JOptionPane.showInputDialog("Latitude?"));

Read in both the latitude and logitude.

Activity 7: Reading the File

Using the example code that we have done in class the past few days, write code that will loop through the wendys.csv file and compare the coordinates the user entered to the coordinates from the .csv file. Note that the 0 position in the .csv is the latitude and the 1 position is the longitude.

Since we want to find the closest Wendy’s, we need a way to figure out the distance between two sets of GPS coordinates. Here’s your first introduction to using more methods in your own code!

Copy and paste the following method in your Wendys.java file inside the class statement BUT NOT inside main. It needs to be completely separate from main!

GPS Distance Calculation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static double distanceTo(double lat1, double lon1, double lat2, double lon2) {

  double theta = lon1 - lon2;
  double dist = Math.sin(lat1 * Math.PI / 180.0)
          * Math.sin(lat2 * Math.PI / 180.0)
          + Math.cos(lat1 * Math.PI / 180.0)
          * Math.cos(lat2 * Math.PI / 180.0)
          * Math.cos(theta * Math.PI / 180.0);
  dist = Math.acos(dist);
  dist = dist * 180.0 / Math.PI;
  dist = dist * 60 * 1.1515;

  return dist;
}

You can execute this code by doing the following in main in the loop where you are reading the .csv:

Testing Distance
1
double distance = distanceTo(userLat, userLon, wendysLat, wendysLon);

Here, the userLat and userLon are what the user typed in and you saved from the pop up windows and wendysLat and wendysLon are the 0 and 1 columns from the .csv (remember you can get these after you split the line… look at the examples from class!).

The result distance here is the distance in miles.

Loop through the entire file, keeping up with which Wendy’s gave you the shortest distance from the user’s coordinates to that Wendy’s coordinates. Save that information!

Activity 7: Google Maps

Now let’s put it on a map!

We can take the address (which is the combination of columns 4, 5, and 6 from the .csv) and create a web address object (URI) that Java can use to open your computer’s default browser.

Opening Google Maps
1
2
3
4
// You need to create the address variable below by concatenating columns 4, 5, and 6 from the .csv
String URL = "http://maps.google.com/maps?q=" + address;
URL = URL.replace(" ", "%20");
Desktop.getDesktop().browse(new URI(URL));

We use that replace command because URL’s aren’t allowed to have spaces in them, so we have to replace the spaces with the encoded equivalent, which is %20.

Activity 8: Run Multiple Times

Give it a shot and see what Wendy’s you can find!

Submission

We’ll continue to use the lab submission page for this lab. Only one partner needs to submit; the system will keep track of partners for you.

You must submit on time! Even if you don’t finish, submit what you have.

Lab 5 - February 12 - Hoo Libs

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

Try to find a new lab partner for this week! Meet new people! See previous lab sessions for a description of pair programming if necessary.

Activity 3: Starting Out

Let’s again create a new project. Call it HooLibs. Create a new .java file called HooLibs.java.

Here’s the image we will use this week. Download it and drag it into your project folder (not src).

MadLibs

Activity 4: Dialog Windows

We are again going to use dialog windows. Here’s a quick refresher:

To make a MessageDialog pop up (where the user is just told information), you use the following code:

MessageDialog
1
JOptionPane.showMessageDialog(null, "Text", "Title", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("nameOfPictureFile.png"));

To make a InputDialog pop up (where the user types in a String), you use the following code:

InputDialog
1
String returnText = (String) JOptionPane.showInputDialog(null, "Text", "Title", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("nameOfPictureFile.png"), null, null);

We will add one more this time - the ConfirmDialog, which provides a Yes/No for the user to choose from:

ConfirmDialog
1
int reply = JOptionPane.showConfirmDialog(null, "Yes/No Question", "Title", JOptionPane.YES_NO_OPTION, 0, new ImageIcon("nameOfPictureFile.png"));

To use the ConfirmDialog, we need to test what reply is after the window closes. To do this, we check to see if reply has the same value as Yes as defined by the JOptionPane class. We will use what’s called a constant, which is a value that is used effectively like a flag:

ConfirmDialog Yes/No Test
1
2
3
4
5
if(reply == JOptionPane.YES_OPTION) {
  System.out.println("User clicked Yes!");
} else {
  System.out.println("User clicked No!");
}

Activity 5: Writing Your Stories

A Mad Lib… ahem, a Hoo Lib is a story in which the player is asked to provide certain categories of random words, such as a noun, a verb, an adjective, a proper name, an adverb, a past tense verb, a color, a fruit, an animal… you get the idea. The first thing you need to do is come up with at least three different stories that you’ll have for people to fill out.

To make the code here a (lot) easier, each of the stories has to have the same number of kinds of words. So, if one story has three nouns, one name, two verbs, and an animal, all three should have the same number of those exact things. However, they can be in any order you want.

We’re going to use an array of Strings, much like we did last week with Magic 8 Ball. Setup your array of Strings like this:

String Array
1
2
3
4
5
String story1 = "Today the noun1 went around town and verb1 all over the place.";
String story2 = "I really enjoy eating noun1 right after I verb1.";
String story3 = "The first year that came to office hours today brought his noun1 so that I could verb1 it."
      
String[] stories = {story1, story2, story3};

Notice how we have what almost looks like variable names in each of the stories. Create unique names for each of your word replacement locations - we’re going to use some methods in String to replace them with what the user types in.

You can use this code, but you need to write your own stories! They should have at least 5 things for the user to type in (but you can do more). Whatever you want to do is fine… but keep them clean please. Amusing UVa stories are typically the best ones.

Here’s one of my favorites that I found online (however it’s a bit long for this lab):

MichaelBay

Activity 6: Let’s Make Some Windows

Here are the windows you should have and the order they should pop up:

  • A welcome MessageDialog (much like last week)
  • An InputDialog for each word you need the user to provide (so, at least 5 of these, but maybe more) - ask the user to provide a noun (or whatever)
  • A MessageDialog showing the story

At this point, with what we have currently taught you, it’s best to NOT try to make a loop around one InputDialog to read in what the user types. Just trust us. Just make 5 separate windows that stores the text into 5 separate variables.

Now, the question is which story should the program use each time it is run? Create a Random object, get a random int, and then select the story almost exactly like you did last week. Store a copy of that story in a variable called currentStory. (Refer to last week’s lab here if you need a refresher of what the code looks like.)

Activity 7: Word Replacement

Time to replace all those placeholders with the words the user provided! To accomplish this, we’ll use String’s .replace() method.

Assume you stored the first noun the user gave you in a varaible called usernoun1 and assume that this replaces “noun1” in your story.

The code to do the replacement would be:

String .replace()
1
currentStory = currentStory.replace("noun1", usernoun1);

This code will look for every location that “noun1” appears in the story and replace it with whatever the user typed and is stored in the variable usernoun1. Repeat this process for each word the user provides.

Then display the completed story in a final MessageDialog!

Activity 7: Test Your Program!

Run your program a few times to verifiy that it works! If it doesn’t, go back through the steps and try to trace your code to find the error.

Activity 8: Run Multiple Times

We would like your program to prompt the user to see if they want to run through the program again. After you show the window with the story to the user, now show a ConfirmDialog as shown above to ask the user if they would like to do another. If they say yes, you should loop back to the top and ask the user for the first word again. Remember: you’ll need a new random number to get a (possibly) new story! Make sure you handle this!

Which loop would work best here?

  • for is best when you know exactly how many times the loop will run
  • while is best when you don’t know how many times the loop will run (such as if you were reading a file)
  • do while is best when you want the code to run at least once, then check some condition to know whether to run again

Check your text or the lecture notes for the syntax if you can’t remember what it looks like.

Add the appropriate loop so the user can play over and over!

Submission

We’ll continue to use the lab submission page for this lab. Only one partner needs to submit; the system will keep track of partners for you.

You must submit on time! Even if you don’t finish, submit what you have.

Lab 4 - February 5 - Magic 8 Ball

Winners of the turtle art contest:

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

Try to find a new lab partner for this week! Meet new people! See previous lab sessions for a description of pair programming if necessary.

Activity 3: Starting Out

This week, instead of using the console, we’re going to write a program that uses pop-up dialog windows. The code here will look a bit different, but the concepts are the same.

When a dialog opens, it will either complete and exit (like a message window) or it will return the text that the user typed. We’ll use both of these types in this program.

First, grab this image and save it somewhere you can find it:

magic8ball.png

In Eclipse, create a new project for today. Call it “Magic 8 Ball.”

Drag and drop the image you just downloaded into your project folder, NOT into the src folder. It should be at the same depth as the src folder - not inside it.

Now, create a new .java Class file called “Magic8Ball.java”.

Activity 4: Dialog Windows

There are two types of dialog windows that you will use for this project - one that just displays information and one that asks the user for information.

The type that displays information is called a MessageDialog.

To make a MessageDialog pop up, you use the following code:

MessageDialog
1
JOptionPane.showMessageDialog(null, "Text", "Title", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("nameOfPictureFile.png"));

This is slightly different than what you’ll see in the book. Specifically, there are more parameters here. That’s so we can display the picutre on the window as well.

You should replace “Text”, “Title”, and “nameOfPictureFile.png” with the appropriate information when you use this. The program will pause when this dialog is up and will wait for the user to hit OK to continue.

The second type of dialog you will use is called an InputDialog.

To make an InputDialog pop up, you use the following code:

InputDialog
1
String returnText = (String) JOptionPane.showInputDialog(null, "Text", "Title", JOptionPane.INFORMATION_MESSAGE, new ImageIcon("nameOfPictureFile.png"), null, null);

This is slightly different than what you’ll see in the book. Specifically, there are more parameters here. That’s so we can display the picutre on the window as well.

You should replace “Text”, “Title”, and “nameOfPictureFile.png” with the appropriate information when you use this. The program will pause when this dialog is up and will wait for the user to type something and then hit OK to continue.

Here is what these windows might look like when you are done:

initialscreen.png

questionscreen.png

answerscreen.png

Remember after you put this code in to hit Ctrl-Shift-O to organize your imports so Java can find these classes!

Activity 5: How to get a Random Number

In order for the Magic 8 Ball to work, we need to be able to pick out a random answer from a list of pre-determined answers. Let’s start with how to get a random number.

Make a separate class called GetRandom.java.

Inside that class’s main method, try out the following code (note you’ll have to do Ctrl-Shift-O / CMD-Shift-O to fix the imports):

GetRandom.java
1
2
3
Random rand = new Random();
int randomNumber = rand.nextInt(10);
System.out.println(randomNumber);

Run this a bunch of times and note the answers you get.

What number did you not get that you thought you might?

rand.nextInt(x) will give you an int where 0 <= randomNumber < x.

Activity 6: Complete the Code

Your program should perform the following steps:

  1. Welcome the user to the program
  2. Ask the user a question
  3. Randomly choose an answer from a list of possible answers
  4. Display the question back to the user with the randomly chosen answer
  5. Call System.exit(0); to fully quit the program and make sure no extra dialog windows are open.

Using the code in Activity 4, you can easily do #1, #2 and #4. #5 is provided for you right there. So how do you do #3?

Well, first you need a set of answers. You could use the “official answers,” as shown here on Wikipedia. Or you can make your own!

Make a list of possible answers like this:

possibleAnswers
1
String[] possibleAnswers = {"Answer 1", "Answer 2", "Answer 3" ...};

(Get rid of the “…” by the way)

Then, create an instance of the Random class and use it as shown above to get a random number to then pull out a particular answer.

possibleAnswers
1
String currentAnswer = possibleAnswers[randomNumber];

Using the steps above, put together Magic8Ball.java so that it works like the example!

Submission

Use the lab submission page for this lab. Only one partner needs to submit; the system will keep track of partners for you.

You must submit on time! Even if you don’t finish, submit what you have.

Lab 3 - January 29 - Turtle Art Contest

Activity 1: Login and Record Attendance

We will be taking roll in lab each week! Please come to your assigned lab to be counted present!

Click “Lab Attendance” on the left-hand menu in Collab to register your attendance and keep up with your lab grade.
YOU MUST CLICK THE LARGE GREEN OR YELLOW BUTTON FOR YOUR ATTENDANCE TO COUNT!!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

We will use a model called “pair programming” in this class. There are a few things to know about successful pairing under this model:

  • 2 minds, 1 focus. If at any point the two of you are doing distinct things, such as each typing on your own computer or each looking at your own piece of paper, then you are not pairing properly.
  • Driver and Navigator. At any given point in time, one partner will be the “driver”, controlling the keyboard, pencil, or other tool currently being used. The other will be the “navigator,” observing and commenting on the driver’s actions
  • Equality and Communication. Driver and navigator are equal partners; the ideas of both are equally important, and both should talk, both should listen when the other speaks, and both should treat the other’s ideas with respect.
  • Switch Roles. Which partner is driving should change at least every 15-20 minutes, if not more often.

Pairing in this model has many advantages both from a productivity and learning standpoint. One of these is generally an increase the intensity of focus, which can get tiring. Feel free to take breaks every now and then, but try not to distract other pairs during your breaks.

For more hints on successful pairing, you might want to watch this 10-minute video on your own time.

Activity 3: Art Contest

Your goal with this lab is to make the neatest picture you can using the turtle and any example code we have provided. You can use any of the code posted on the lecture notes as a starting point, or you can use your own.

Make sure to look at the Turtle and World API in the lecture notes. (Remember: the API is the “list of things that you can do with a class”)

Use the myWorld.saveAs(“someImageName.png”) method to save your file. It should be saved into your Eclipse project - you can find this if you browse to your workspace on your computer.

Submission

Submit your .png to the Turtle Art Gallery. The staff will pick our favorite images, with prizes awarded next lab!

Lab 2 - January 22 - Counting Rooms

Activity 1: Test your logins!

If you are in a lab in Olsson 001, try out your Olsson 001 login. If you have trouble, talk to your lab TA.

Activity 2: Pairing

For this and all subsequent labs, you will work in pairs.

We will use a model called “pair programming” in this class. There are a few things to know about successful pairing under this model:

  • 2 minds, 1 focus. If at any point the two of you are doing distinct things, such as each typing on your own computer or each looking at your own piece of paper, then you are not pairing properly.
  • Driver and Navigator. At any given point in time, one partner will be the “driver”, controlling the keyboard, pencil, or other tool currently being used. The other will be the “navigator,” observing and commenting on the driver’s actions
  • Equality and Communication. Driver and navigator are equal partners; the ideas of both are equally important, and both should talk, both should listen when the other speaks, and both should treat the other’s ideas with respect.
  • Switch Roles. Which partner is driving should change at least every 15-20 minutes, if not more often.

Pairing in this model has many advantages both from a productivity and learning standpoint. One of these is generally an increase the intensity of focus, which can get tiring. Feel free to take breaks every now and then, but try not to distract other pairs during your breaks.

For more hints on successful pairing, you might want to watch this 10-minute video on your own time.

Activity 3: Grid of doors

Picture of door space

For this lab we will be programming a robot that has been dropped into a grid of square rooms. Each wall of each room has been painted a different color: the North wall is Neon, the East wall is Eggplant, the South wall is Sandy, and the West wall is Wallnut. Walls between rooms have doors in them, but walls on the edge do not. All of the doors are closed initially.

The robot knows how to

  • Check N (or Check E, or S, or W) to see if there is a door on that wall of its current room;
  • Go N (or E or S or W) to move one room over; and
  • Do basic math and remember numbers

If you ask it to Go through a wall that does not have a door, it isn’t smart enough to know it can’t so it will walk into the wall and damage itself.

We won’t be super formal in this lab. If we can tell what you are asking the robot to do, that’s good enough for us.

Activity 3.1: Simple Square

Suppose the robot is dropped into a square grid of rooms and starts in the north-west corner of the grid. Come up with an algorithm that the robot can use to figure out how many rooms are in the grid.

Is there any size grid for which your algorithm does not work? How about on a 1-by-1, or a 1000-by-1000?

In a 3-by-3 grid, how many times will the robot have to move through a door to run your algorithm? How about a 4-by-4? An n-by-n?

Assume that we want to save on robot fuel. Can you make an algorithm that uses fewer moves for the same size grid?

Once you have an algorithm you think is general (works for all size squares) and efficient (uses few moves), submit it as Lab 02 Activity 3.1 in the assignments tab on Collab. Include a simple statement about how many moves it takes, on an n-by-n grid the robot moves through 2n+5 doors or something like that.

One partner should submit the algorithm and its efficiency; the other one should submit just the computing ID of the partner that submitted it (e.g., just mst3k, no other text at all).

Activity 3.2: Simple Rectangular

Suppose the robot is dropped into a rectangular (not necessarily square) grid of rooms and starts in the north-west corner of the grid. Come up with an algorithm that the robot can use to figure out how many rooms are in the grid.

Submit an algorithm for this case as Lab 02 Activity 3.2, including a description of the number of moves needed for an n-by-m grid. Again, one partner submits, the other submits the id of the one who submitted.

If your 3.1 algorithm still works, you are welcome to submit it again for 3.2.

Activity 3.3: Rectangular

Suppose the robot is dropped into a rectangular (not necessarily square) grid of rooms and might start in any arbitrary room in the grid. Come up with an algorithm that the robot can use to figure out how many rooms are in the grid.

Submit an algorithm for this case as Lab 02 Activity 3.3, including a description of the number of number of moves your robot will make for an n-by-m grid. Since this will probably depend on the starting location of the robot, just tell us the biggest number you could see (assuming the robot started in the worst possible room). Again, one partner submits, the other submits the id of the one who submitted.

If one of your previous two algorithms still works, you are welcome to submit it again for 3.3.

Activity 3.4: Stranger Grids

See how general you can make your algorithm. Can you get it to work on diamond-shaped grids of rooms? Grids with more complicated outlines? Grids where some rooms are missing in the middle? Grids where some walls between two rooms that do exist don’t have doors? Arbitrary mazes of rooms?

Submit the most general algorithm you can come up with as Lab 02 Activity 3.4. At the beginning of the submission, include a description of the kinds of grids you think it can handle. Again, one partner submits, the other submits the id of the one who submitted.

We are not looking for any particular functionality in activity 3.4; if you can’t get any more than 3.3 done, submit 3.3 and tell us it’s as much as you could do in the time we gave you.

Lab 1 - January 15 - Getting Started

Lab this week is optional in that we will not be taking roll. However, this is an opportunity to come to ensure that you have Java and Eclipse installed and working properly on your laptops. If you do not come to lab, we will assume you have taken care of this yourself and you are ready to go when we start coding in lecture next week. So, if you have any doubts, come on down to lab, meet some of the TAs, and make sure you’re laptop is setup and ready to go!

Java

Windows
Mac
Windows 32-Bit

If you want it from the source:
Java Download from Oracle

Eclipse

Most people use these options:
Windows 64-Bit
Mac 64-Bit

Only if you know you are using 32-bit use these options:
Windows 32-Bit
Mac 32-Bit

If you want it from the source:
Eclipse Download from eclipse.org

Make sure that if you get matching 64-bit or 32-bit versions of Java and Eclipse! They both have to be the same! (In general, unless something is weird with your machine (either Windows or Mac) just get the 64-bit version of each.)