Friday, January 30, 2015

Java Game - Cat Simulator 2015

In order to demonstrate the abilities we've learned in Java over the course of the first three chapters, Ché and I made a program wherein the user names a cat and tells the program what to do with it. This involves petting, giving, watching, or exiting.

Ché has more information about the program itself on his blogspot post for it, we worked together making it. It can be found here.

Wednesday, January 28, 2015

Head-First Java - Chapter 3 - What I Learned

This chapter was all about variable types and their functions. It helped to distinguish between objects and classes, and showed how the whole "Blah blah1 = new Blah();" thing works in terms of using reference variables to control objects. Some other things I got out of this were:


  • Primitive variables come in eight flavors - four relating to integers, two relating to non-integer real numbers (i.e. with decimal points), one for booleans, and one for characters
    • Booleans (boolean), like always, are either True or False
    • Characters (char), can take up 16 bits and assign variables to letters
    • The four integer variables are byte, short, int, and long. They can hold 8 bits, 16 bits, 32 bits, and 64 bits, respectively. They're all used for numerical values, but each are used depending on the size of the value
      • An important thing to note is that a good analogy for these numeric variables are different sized cups. You can redefine smaller values that fit into smaller types as bigger types, like how you can pour something from a small cup into a larger cup. However, you cannot redefine values in bigger types as smaller types, even if they'd technically fit in the bit-constraint. The JVM doesn't want to pour stuff from a big cup into a smaller cup, because it doesn't know if it'd fit or not and prefers to err on the side of caution.
    • Numbers with decimal points (floats, non-integer numbers) have two primitive variable types - floats, which can hold 32 bits, and doubles, which can hold 64 bits. I have no clue why they call the larger version of the float a double - it seems like a pretty unspecific choice of diction for such a particular data type
  • Variables have to start with a letter, underscore, or a dollar sign
    • This helped explain to me why I oftentimes see the $ symbol in Java code
    • Numbers can only be used after the first character in a variable name
  • There are also certain names that cannot be used for a variable, because they are used elsewhere in Java (e.g. class, finally, assert, etc.)
  • Object reference variables are basically remote controls
    • Imagine a line of code that reads "Dog d = new Dog();". This creates a Dog object reference variable, referencing a dog object. This variable holds a sort of remote control called "d", which controls a Dog() object
    • The next line could read "d.bark();", which tells the remote to hit the "bark" button, or call the bark() function on the specific Dog() object that the reference variable is referring to
  • The bit depth of object reference variables aren't relevant
  • As long as a reference variable is assigned to a particular object, that object stays active. If an object remains inactive, it is sent into the "garbage heap" and is no longer reference-able or usable
  • An array variable creates a sort of "tray of cups", with each cup being a variable that holds a particular value

Here's some dog code:


class Dog {
    String name;
    public static void main (String[] args) {
        //make a Dog object and access it
        Dog dog1 = new Dog();
        dog1.bark();
        dog1.name = "Bart";

        //now make a Dog array
        Dog[] myDogs = new Dog[3];
        //and put some dogs in it
        myDogs[0] = new Dog();
        myDogs[1] = new Dog();
        myDogs[2] = dog1;

        //now access the Dogs using the array references
        myDogs[0].name = "Fred";
        myDogs[1].name = "Marge";

        //Hmmm... what is myDog[2] name?
        System.out.print("last dog's name is ");
        System.out.println("myDogs[2].name);

        //new loop through the array, and tell all dogs to bark
        int x = 0;
        while(x < myDogs.length) {
            myDogs[x].bark();
            x = x + 1;
        }
    }

    public void bark() {
        System.out.println(name + " says Ruff!");
    }

    public void cat();
    public void chaseCat();
}
 

Tuesday, January 20, 2015

Head-First Java - Chapter 2 - What I Learned

This chapter helped me understand the basics of Object Oriented Programming (OOP). I really like the concept of OOP, it turns programming from a laundry list of disjointed code to an organized set of classes and objects that can be changed or added to very easily. It makes more sense in relation to the real world.

Some other things I learned include:
  • main() should only be used to test real classes and/or to launch and start a Java application
  • Objects can "talk" to teach other by calling methods on each other
  • "Global" variables don't really exist in Java OOP, but later we'll learn how using public and static can make a variable behave like a global one
  • A class is like a recipe, whereas objects are like cookies
  • Subclasses can inherit instance variables and methods from superclasses 
 There was no actual code to run in this chapter - it was mostly conceptual.

Tuesday, January 13, 2015

Head-First Java - Chapter 1 - What I Learned

  • The main thing I learned was how the syntax of Java differs from Python, like how:
    • All lines end in semicolons, like how most sentences end in periods or other forms of punctuation
    • Functions and loops are "boxed in" with curly braces, to differentiate the code within them that loops and the code outside of them that runs independently from it
    • White space generally doesn't matter, but can be used to organize the program and help aid in the readability of it
    • Object-oriented programming basically just means chopping up a big, procedural program into seperate classes and methods that would make sense in real life (e.g. class Animal, object Dog)
    • I used to get scared of Java because of the dreaded "public static void main (String[] args)" line, because I never had any clue what it meant. But now I understand that public makes the code, well public, void means there's no return value, and main is just the name of the current method, which is a group of code within a class
    • Most concepts from Scratch and Python, like how integers, strings, Booleans, expressions, loops, etc. work, are nearly the same in Java, but with subtle differences in syntax (e.g. String has to be capitalized when declaring a string variable in Java)

  • I made a separate post about the "99 Bottles of Beer on the Wall" problem, which can be found here.

  • I also made the "PhraseOMatic" program, according to how the chapter did it (code below). I was able to work my way through what was happening while I wrote it, and confirmed my beliefs on the following page, which explained the code:
    • The code creates three lists of words
    • Sets the length of each list, in terms of how many words there are in each one, to a variable
    • Generates a random number within the length of each list, creates a variable for each list with this number (the random function uses a value between 0 and 1, multiplies the length by it, and rounds the float to an integer, in essence creating a random number)
    • Creates a string that combines the three different random values for each list, pulling out a word from each list and concatenating them together
    • Finally, this concatenation is combined with a final string that puts the three words into a proper sentence, and prints that string
public class PhraseOMatic {
  public static void main (String[] args) {   

    String[] wordListOne = {"24/7", "multi-Tier", "30,000 foot", "B-to-B", "win-win", "front-end", "web-based", "pervasive", "smart", "six-sigma", "critical-path", "dynamic"};

    String[] wordListTwo = {"empowered", "sticky", "value-added", "oriented", "centric", "distributed", "clustered", "branded", "outside-the-box", "positioned", "networked", "focused", "leveraged", "aligned", "targeted", "shared", "cooperative", "accelerated"};

    String[] wordListThree = {"process", "tipping-point", "solution", "architecture", "core competency", "strategy", "mindshare","portal", "space", "vision", "paradigm", "mission"};

int oneLength = wordListOne.length;
int twoLength = wordListTwo.length;
int threeLength = wordListThree.legth;

int rand1 = (int) (Math.random() * oneLength);
int rand2 = (int) (Math.random() * twoLength);
int rand3 = (int) (Math.random() * threeLength);

String phrase = wordListOne[rand1] + " " + wordListTwo[rand2] + " " + wordListThree[rand3];

System.out.println("What we need is a " + phrase); 

  }

Friday, January 9, 2015

Java - 99 Bottles of Beer on the Wall *FIX*

In the Heads-On Java activity "Coding a Serious Business Application", it showed us a finished program that runs through the song "99 Bottles of Beer on the Wall", but with a small problem that we needed to find and fix. 

The problem ended up being an if statement put before the rest of the content within the while loop, that needed to be integrated farther down. The if statement regarded beerNum equaling 1, changing the word from "bottles" to "bottle" so it made sense with a quantity of 1. It was originally before the "beerNum = beerNum - 1" statement, which decreases the amount of bottles. It needed to be after it, so the program can check for the bottle equaling 1 before it says the next phrase. I commented where the if statement used to be, and highlighted where I put it to fix the program.

public class BeerSong {

    public static void main(String[] args) {

        int beerNum = 99;
        String word = "bottles";
        
        while (beerNum > 0) {

            //This is where the if statment used to be
            
            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) {
                word = "bottle";
            }            
            
            if (beerNum > 0) {
                System.out.println(beerNum + " " + word + " of beer on the wall");
            } else {
                System.out.println("No more bottles of beer on the wall");
            }
        }
    }  
}