Chapter 5. Writing a Program: Extra-Strength Methods

image with no caption

Let’s put some muscle in our methods. We dabbled with variables, played with a few objects, and wrote a little code. But we were weak. We need more tools. Like operators. We need more operators so we can do something a little more interesting than, say, bark. And loops. We need loops, but what’s with the wimpy while loops? We need for loops if we’re really serious. Might be useful to generate random numbers. And turn a String into an int, yeah, that would be cool. Better learn that too. And why don’t we learn it all by building something real, to see what it’s like to write (and test) a program from scratch. Maybe a game, like Battleships. That’s a heavy-lifting task, so it’ll take two chapters to finish. We’ll build a simple version in this chapter, and then build a more powerful deluxe version in Chapter 6.

Let’s build a Battleship-style game: “Sink a Dot Com”

It’s you against the computer, but unlike the real Battleship game, in this one you don’t place any ships of your own. Instead, your job is to sink the computer’s ships in the fewest number of guesses.

Oh, and we aren’t sinking ships. We’re killing Dot Coms. (Thus establishing business relevancy so you can expense the cost of this book).

Goal: Sink all of the computer’s Dot Coms in the fewest number of guesses. You’re given a rating or level, based on how well you perform.

Get Head First Java, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.