BBC (Brian's Boot Camp)

Not to be confused with the British Broadcasting Corporation, the BBC will focus on Brian's fast paced journey of the mastery of the Java programming language.

Wednesday, September 27, 2006

Masking

How about a nice intro to masking? Write the body of this function:


public int extractBit(int num, int pos);


This function should return the value of the bit of "num" at postion "pos".

For example: extractBit(5, 0) would return one, whereas extractBit(16, 2) would return zero.

Hint: Start by looking at how bitwise & works.

Saturday, March 05, 2005

Assignment #2 Answer

Oh man, oh man. I can't believe I ate the whole thing.

After doing a little Google search to help me out on how to use SimpleDateFormat I spent a while scratching my head wondering why you wanted to me to use GregorianCalendar or Calendar. Now I see.

import java.text.*; 
import java.util.*;

public class DateParse {
public static void main(String[] arguments) {

int month = 2;
int day = 3;
int year = 1976;

if (2 < arguments.length) {
month = Integer.parseInt(arguments[0]);
day = Integer.parseInt(arguments[1]);
year = Integer.parseInt(arguments[2]);
}
GregorianCalendar gregCal = new GregorianCalendar(year, (month - 1), day);

SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy");
System.out.println(sdf.format(gregCal.getTime()));
}
}

Thursday, March 03, 2005

Assignment #5 The Odds are Stacktropolised Against You

Alright, after that forced title, here's an exercise that will primarily teach you how to read/trace through/modify someone else's code. You'll also get exposure with managing projects with more than one source file (Stacktropolis has 15).

First things first: Stacktropolis: An Overview:
Stacktropolis is a Tetris clone; the fundamental rules of Tetris apply. The object is to rotate the falling blocks in order to fit them in and clear lines. When a line is cleared the remaining blocks will fall accordingly.

Stacktropolis' twist is that it introduces the idea of the reward gauge. I loved the reward system in the original Monkey Target from Super Monkey Ball (Turning off wind, Magnet Ball, etc). I like the idea that as you do better, your reward is progressively better.

So at the bottom of the game is the reward gauge. To fill up the gauge you need to clear lines with green balls in them. Each green ball that is cleared raises the gauge by one unit. Watch out though, if you clear a line with a red ball, your reward gauge drops to zero. The idea then becomes balancing between trying to get the best reward possible and "caching out" the gauge before clearing a line with a red ball.

At any point you can cach out your current reward (by pressing the 'A' key), or take the equivalent point value (by pressing the 'Z' key). The rewards, in order of least to best, are:

  • A single white block is put in your queue as the next block. This is useful for "filling in the cracks".
  • The drill-down block. This block will essentially clear a column -- it will continue to fall until it hits the bottom, removing any blocks in its path.
  • The delete line reward. This starts a moving line from top to bottom. When the player hits "D" the current line is removed.
  • Hazards to Rewards. This reward changes all the red balls into green.
  • Gravity Well (my favorite). This invokes gravity on the blocks by having all the blocks fall as far as they can, filling in the gaps, clearing lines as they go.
  • Clear Blocks Reward. The highest reward simply clears all the existing blocks on the screen.
The Assignment:
  • I emailed you the codebase for Stacktropolis a while back, so you already have everything you need from me. To build Stacktropolis you'll need to download Ant, which is a build tool similar to Make. Once you've downloaded Ant and extracted it, you'll need to set two environment variables, ANT_HOME and JAVA_HOME, and add ANT_HOME\bin to your path. The installation instructions should have details on that. Once Ant is configured, go to the st directory (of Stacktropolis) and type "ant" to build it.
  • Once built, play around with the game. Get a feel for it. Try out all the rewards, etc.
  • Once you feel comfortable with the game itself, try reading through some of the source. Trace through the startup process, insert a System.out.println() statement here and there and rebuild it to see if it did what you thought it was going to.
  • Once you're relatively comfortable with all that, make the following modification: Change the first and second rewards (the single block and the drill down) to have the option to "detonate" at any point during their trip down if the player hits the "D" key. The detonation should be a clearing of blocks within a certain radius of the current position of the reward block. You can play around with what that radius should be (whatever seems to serve the game balance). Blocks left hanging in space should drop accordingly.
  • You're in someone else's kitchen now, follow the coding style and comment what you do accordingly. Stacktropolis is very light on the comments since I never intended anyone else to see it, but you can get an indication of the style of comments (Javadoc).
So there you go. Good luck.

Wednesday, March 02, 2005

Assignment #4: The Ubiquitous Bouncing Balls

Ah, the bouncing balls app. A program Paul had me write in the early days, and then in turn that I asked Dave to write a year later, and now 7 years after that, you get to take a wack at this timeless classic (hmmm, wacking at balls?). This assignment covers GUI, Threads, animation, drawing, creating your own classes, and events; it's kind of a non-interactive game. Just in time for your solo weekend too:

Write a program that displays a frame. The top part of the frame should have a black background, this is the ball cage. The bottom of the frame contains a button labeled "Add Ball". When pressed, it will add a "ball" (a circle) to the cage that will head off in some direction and "bounce" off the borders of the cage indefinitely. Subsequent presses of the button will continue to add balls.

Notes:
1) It's up to you of course, but now is a good time to start doing some Object Oriented design. Consider writing a Ball class. You could even go crazy and write a BallCage class too...

2)Some extra options: make each ball a random color, and give it an initial random direction and velocity (a bunch of balls all the same color going the same direction and speed isn't very interesting).

3) Don't worry about collision detection between balls -- just the walls.

This will be your most ambitious effort yet. But for your reference, I wrote this from stratch in real-time, in front of a high school class in a 50 minute class period.

Assignment #3 Answer

This morning, I put chapter 12 and Assignment 3 behind me. At the rist of invoking the Sin of Pride, I'm pretty proud of myself. Huzzah indeed.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class StringSwapper extends JFrame implements ActionListener {
JTextField inputField = new JTextField("String", 5);
JButton pressMe = new JButton("Press Me");
JTextField outputField = new JTextField(5);

public StringSwapper() {
super("Convert a String");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
pressMe.addActionListener(this);

getContentPane().setLayout(flow);
getContentPane().add(inputField);
getContentPane().add(pressMe);
getContentPane().add(outputField);
pack();
setVisible(true);
}

public void actionPerformed(ActionEvent evt) {
String input = new String(inputField.getText());
int len = input.length();
char[] gnirts = new char[len];

for (int i = len - 1, c = 0; i > -1; i--, c++) {
gnirts[c] = input.charAt(i);
}

String output = new String(gnirts);
outputField.setText(output);
setTitle("Huzzah!");
}

public static void main(String[] args) {
StringSwapper ss = new StringSwapper();
}
}

Thursday, February 24, 2005

Parsing a string for boolean

In the examples in the 21 Days book, there are numerous instances where a String is parsed to produce some other value type like an int or a float using a statement such as i = int.parseInt(string). This makes perfect sense to me.

One of the exercises says this: Create a modified version of the Storefront project that includes a noDiscount variable for each item. When this variable is true, sell the item at the retail price.
Seems simple enough. I took the GiftShop class which defines the items for sale and added a "TRUE" or "FALSE" to each of them; that's not where the problem is. Through a couple of method calls the string values assigned to each item in GiftShop get handed off to an Item class. Item takes all of the strings from GiftShop and assigns them to String variables or parses them and assigns them to ints or doubles. Both of those two operations use the following two statements:
retail = Double.parseDouble(retailIn);
quantity = Integer.parseInt(quanIn);

Pretty straightforward at this point.

So I get to thinking, "Well I know that ints and doubles are primitive but that there are objects which correspond to each of the primitives; that's what the whole Double.parseDouble bit is about. I know there is also a Boolean object, so I'll do the same thing for my noDiscount variable: I'll use something like this:
private boolean = noDiscount;
/* unrelated code
when the String values come in from GiftShop, the "TRUE" or "FALSE" value comes in as "String discountIn"
so then I do this: */
noDiscount = Boolean.parseBoolean(discountIn);


But it doesn't work. When I compile the class, I get the following error back:

Item.java:18: cannot resolve symbol
symbol : method parseBoolean (java.lang.String)
location: class java.lang.Boolean
noDiscount = Boolean.parseBoolean(discountIn);
^
1 error


But when I look at the API documentation, the method is there and is listed exactly the same as is the equivalent method for Integer:
static boolean | parseBoolean(String s) | Parses the string argument as a boolean.
and
static int | parseInt(String s) | Parses the string argument as a signed decimal integer.

What gives?

Monday, February 21, 2005

Another small milestone

While I'm waiting for Outlook to launch, I'll throw this up. At the beginning of the 21 Days book, the author states that the portability of Java's code allows developers to Write one, debug everywhere; funny. So far, any code that I've used for any assignments, examples, or exercises has worked fine on my laptop (where I'm using Eclipse) or on my Mac (where I'm using vim and the command line tools). Until chapter 9 which introduces Swing. The classes would compile fine on either platform, but when I ran them on OS X, I'd get the following output:

Exception in thread "main" java.lang.Error: Do not use FormatFrame.add() use FormatFrame.getContentPane().add() instead
at javax.swing.JFrame.createRootPaneException(JFrame.java:465)
at javax.swing.JFrame.addImpl(JFrame.java:491)
at java.awt.Container.add(Container.java:307)
at FormatFrame.(FormatFrame.java:24)
at FormatFrame.main(FormatFrame.java:29)

shell returned 1

I managed to track the problem down to the line add(panel); which added a JPanel to JFrame FormatFrame. Based on the error, it looked like the runtime environment wanted the getContentPane().add() method used rather than the add() method. Sure enough; altered that line of code and it compiled and ran successfully. Huzzah! On to chapter 10...

A Question of Style

Our friend Paul is right is point out that a budding Java developer should be pointed toward the Java Style Guide early to reinforce those positive style habits.

Java in 21 Days Topics

During an offline conversation with Sten (well, it was through e-mail so I guess even it was online) we discussed posting the chapter topics for the Java in 21 Days book that I'm working through. So here they are, by week:


  1. Week 1


    1. Day 1: Getting Started with Java

    2. Day 2: The ABCs of Programming

    3. Day 3: Working with Objects

    4. Day 4: Lists, Logic, and Loops

    5. Day 5: Creating Classes & Methods

    6. Day 6: Packages, Interfaces, and Other Class Functions

    7. Day 7: Threads, Exceptions, and Assertions


  2. Week 2

    1. Day 8: Data Structures

    2. Day 9: Working with Swing

    3. Day 10: Building a Swing Interface

    4. Day 11: Responding to User Input

    5. Day 12: Arranging Components on a User Interface

    6. Day 13: Using Color, Fonts, and Graphics

    7. Day 14: Writing Java Applets and Java Web Start Applications

  3. Week 3

    1. Day 15: Working with Input and Output

    2. Day 16: Serializing and Examining Objects

    3. Day 17: Communicating Across the Internet

    4. Day 18: JavaSound

    5. Day 19: Creating and Using JavaBeans

    6. Day 20: Reading and Writing Data Using JDBC and XML

    7. Day 21: Writing Java Servlets and JavaServer Pages



I think the chapter names are fairly descriptive as far as what they cover, but it would take me forever to post all of the subtopics for all of the chapters. If any clarification is required, please let me know and I'll drill down where necessary. I'm just about to start reading Day 9. Like right this very minute...

Friday, February 18, 2005

A Personal Milestone

Well, I'm very excited. I called in Java...er...sick to work on Java today. Slow going, but I made progress. After spending a while reading, I went back to do the exercises from the chapters. I instantly recognized the first exercise: it was the one that basically made me decide a few months ago that, if I couldn't make the time to study every day, it wasn't worth going after. If only I'd known then what I know now...

So I struck out with my pencil and paper. Sometimes I am amazed how much clear thinking can be done with a piece of blank paper and a pencil rather than typing things out on screen. Here is the assignment:
Using the countDays() method from the DayCounter application, create an application that displays every date in a given year in a single list from January 1 to December 31.

The last time I worked on this exercise, I struggled with it for hours. Compiling what I thought would work again and again just to find that the code wouldn't compile each and every time. This time, after a little pencil work (just for the record, 5 lines of pseudocode and three lines of actual code), I took DayCounter and fashioned it into a functioning application in about twenty minutes. The only compiler error I got was because I had left the ";" off the m++;. I'm so excited! Here is the code; I used the countDays method without altering it.

class ExerciseOne {
public static void main(String[] arguments) {
int yearIn = 2004;
int m = 1;
int d = 0;

if (arguments.length > 0)
yearIn = Integer.parseInt(arguments[0]);

while (m < 13) {
d = countDays(m, yearIn);
for (int i = 1; i < d + 1; i++) {
System.out.println(m + "/" + i + "/" + yearIn);
}
m ++;
}
}

static int countDays(int month, int year) {
int count = -1;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
count = 31;
break;
case 4:
case 6:
case 9:
case 11:
count = 30;
break;
case 2:
if (year % 4 == 0)
count = 29;
else
count = 28;
if ((year % 100 == 0) & (year % 400 != 0))
count = 28;
}
return count;
}
}

Huzzah!

Assignment #3: Time to put the G in GUI

When you feel ready to bone up on GUIs, you can tackle this one:

Write a program that displays two text fields and a button in a frame; the layout is up to you. When the button is pressed, it should take the contents from the first text field and display them reversed in the second text field.

Here's a quick mock-up as an example:


Extra Credit: Write it with Swing (pictured), then write it again using the AWT.

Bonus Extra Credit: Write it as one program that takes an input argument on the command line, either -swing or -awt, and display the frame using the appropriate toolkit. Share as much code as possible between the two implementations. Don't get hung up on this one, the important thing here is to expose you to windowing programming.