Tuesday, January 13, 2015

Head First Java Chapter 1

    I read through chapter 1 and did the activities. In this chapter I learned the basics of java. I had no idea that in order to put an else with an if statement you must put it on the same line after the ending '}'.
Like This: 

if (x == 5) {
System.out.println("X = 5");
} else {
System.out.println("X != 5"):
}

    I also learned that empty space doesn't matter and every statement must end in a semi-colon. I leaened the basic structure of a java program which is class-method-statement.

x == 5 or x     ==     5
System.out.println("hi");

    I thought this was the mistake in the Beer program. I had to look back through the chapter to see this. I also learned the basic structure of a java program. The class is used to hold methods, which hold statements. You need a main method in order to start your program. 

    I fixed the Beer program by changing the if statement at the end and adding two if's inside the else. The problem was that one line printed "1 bottles of beer on the wall" which is not proper English. This was partially dealt with towards the beginning of the original program.

package javaapplication1;

public class BeerSong {

    public static void main(String[] args) {
        int beerNum = 99;
        String word = "bottles";
        
        while (beerNum > 0) {
            if (beerNum == 1) {
                word = "bottle"; //Changes bottles to singular if only 1.
            }
            
            System.out.println(beerNum + " " + word + " of beer on the wall");
            System.out.println(beerNum + " " + word + " of beer.");
            System.out.println("Take one down.");
            System.out.println("Pass it around.");
            beerNum = beerNum - 1;
            
            if (beerNum > 1) { //Had to change to 1 to not print '1 bottles of beer...'
                System.out.println(beerNum + " " + word + " of beer on the wall");
            } else {
                if (beerNum == 1) { //Added to make bottles singular when only 1.
                    System.out.println("1 bottle of beer on the wall");
                }
                if (beerNum == 0) { //Moved from original location to this if statement.
                    System.out.println("No more bottles of beer on the wall");
                }
            }
        }
    }

}

No comments:

Post a Comment