Wednesday, March 4, 2015

Head First Java Chapter 5

    In this chapter I learned about casting primitive variables, and using loops and I created a simple 1D game of battleship.

Casting Primitives:
  You can change one type of variable to another by casting it or using the parse command. You cast a variable by typing (TypeOfVariable). Sometimes this isn't possible like when going from a string to an integer so you can use Integer.parseInt().

Using Loops:
  When trying to do something over and over again you can use loops. There are multiple ways to use them. One is by doing this:
for (String name : nameArray) {}   This code is sets name to an element in the array each time
or
for (int i = 0; i < 20; i++) {} This code sets i to a number from 0 to 19  and then iterates that amount of times.

Battleship:
  This is the code that was used in this chapter to create a program like battleship that only uses a 1D array. I added some comments. 

GameHelper gets the users input:











SimpleDotCom contains the list of ships and the code for if you hit or not:



SimpleDotComTestDrive is the class with the main method, it utilizes the other two in order to run the whole thing:


No comments:

Post a Comment