Friday, 30 September 2011

Java: Enumerated Types ( The Table )

Let's dive right into it, tonight! This is what I have for my table class:

Okay, this isn't all of it, but there's some new info in this chunk! Let's start with the enumeration. We have us our positions, but to ensure we have the right rotation later on, instead of having a buttload of conditional statements (if current position is south, next position is west, if current position is west....), we can just set them here with a function, using the return type of the enumeration. Oh god, what's this outlined in red?!? Well, that's (as you can see) an abstract method.

Recall that when we used functions on enumerated types previously, we had to specify which enumeration we were using. Without abstract, we'd still be there, and we'd have to specify everywhere, or whatever. With this abstract, as long as we have a variable of type Position, we can use next() directly on it.

Position p = Position.SOUTH;;

^ Becomes possible, instead of:;

Next, we need to set an array to hold all our players, as well as tell the game where to place our dealer. A new pack is just a given.

The method after that is to actually place the players at the table. An array of null-types isn't much use, so we have to actually initialize the players. This will give the player a name and a position on the table. The method I use within, .ordinal(), is build into the enumerated types. It returns a numerical value of where in the enumeration the (in this case) position is.

Position p = Position.NORTH;
System.out.println( p.ordinal() );

....would return 0 (Remember, programmers count from 0!). We use this since the array needs a numerical position to set the players at.

Now we get into the old stuff again! Dealing the cards. First, we need to shuffle the deck, at which point the dealing position is set to start from the left of the dealer. The for loop is a little messy. For every card, pass one to the current player, then move to the next player. We're almost done! We just need a toString() method for convenience.

We just have a stringbuilder here,  and it creates a string for us with the players position, followed by more stuff.
The line:

p == dealer ? "* " : "  "

is a compressed conditional statement. It's saying: "Is p (current position) the dealer? If so, give me an asterisk. Otherwise, give me a space". In regular if-statements, this could be represented as:

if ( p == dealer ) {
    return "* ";
} else {
    return "  ";

And uh....that's it! Now all we need to do is create a class to join everything together and actually get to dealing cards. Or, what I did was put that functionality within the main method of table, but you should have a main class to actually do things with, normally. I'm just lazy. This you can do on your own, whichever way you decide to do it. Just create an instance of a Table, make sure to seat your players, then deal the cards. At this point, you can print the table and you can see the players' hands.

Fucking...finally. For the next couple of days, I'll be doing some quick review from start to here, very compressed, but just as a recap. If you've got any specific questions, let me know, otherwise:

That's it for now..Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Thursday, 29 September 2011

Java: Enumerated Types ( The Player )

    Not much else to go! Let's think about what our player consists of. Not in a philosophical sense, mind, but only as far as the game gives a crap. The player consists of...a name (To differentiate them from each other) and a hand of cards. This is what I've then got for a player class (If you have something different, share it!):

First in this class, I've got some variables, straightforward enough. Since the size of the player's hand will change, I used an ArrayList to hold them, instead of the standard array I used for the deck. This might cause some problems with empty slots, so best to nip the problem in the bud. We can also, as a bonus, now use this class in other programs that don't require a set number of cards per hand. Next up is the constructor which is there to actually initialize the name. Next, we have newCard, to be used when being dealt cards, since cards are dealt 1 at a time, instead of a huge clump of 13 at once. the toString method is there so the players' hands can be represented, too. That's about it for the player, fairly straightforward.

So we have a player, the deck and the cards that the players will use. We need a table, at this point, as you may have astutely guessed. Y'know, from the title.

We'll want an enumeration for the compass directions of the table, To make sure the program goes in the correct (clockwise) order, we should probably also have some way to tell the program, in the enumeration, which direction is next. We need an array of players, the deck of cards and to specify where the dealer sits. We need a way to seat players where we want and we need to be able to deal cards out.

Go think about this. Try to make one yourself, and tomorrow, I'll show you my version. It's a fairly large class, at least relative to what we've seen up until this point, so I don't want to throw it at you directly after the player class.

That's all, folks!.Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Wednesday, 28 September 2011

Java: Enumerated Types ( The Deck )

Alright mateys, we have our card representation (No images, but lets...avoid those for now. We`re just working with basics!), Well, we can now work on our representation of a deck of these cards. The construction isn`t exactly straightforward, let alone the rest of the class, so let`s do it in parts!

Please remember, that normally, you`ll want to leave some kind of commentary in your code, I don`t just because I explain everything after the screenie, and to save space in the image, which is often over-sized.

Okay, let`s get started, line by line!

1: Declaration of the class, simple enough

3: We make this public so it can be accessed, final because there is no reason it should change and static so it can be accessed everywhere! The name is all caps, slightly out of convention just to denote its importance. Not necessary, up to the programmer.

5: Since the Card class was part of the same project in Netbeans (Or whatever IDE you use), it can be freely accessed from this class. We've got the instance initialization going on, too!

6: Counter for location in the pack!

7:  Each enumeration has this .values() function. This is the documentation for it:
:Returns an array containing the constants of this enum type, in the order they are declared. 
Simple enough to understand, it just gives back an array of all the elements in the enumeration, essentially. So this line is saying: For every suit in the list of suits (Remember, this is a foreach loop, it doesn`t require its own counter to iterate over everything), do the following:

8:  This line, similar to the last, iterates over every potential value in the list of values. Together, 7 & 8 read: "For each possible suit, do the following: For each possible value, do the following:...", or, more simply: "For each value in each suit..."

9: We are finally doing something! 9 is telling the program to actually add a card to the pack, based on which iteration its at. "For each value, in each suit, make a card" is the short form of these 4 lines.

10: This just increments our pack location to put the next card in.

 Okay, so now we have a constructor. What else do we need? In the interest of saving space, I'm compressed a lot of it, but we'll go through line by line so you don't miss anything!

18: This creates a random object. Used to generate random integers and booleans.

19-25: This is just a shuffle function. For every element in the pack, a random number is generated, then that position of card is flipped with the current position of card.

26: This is just a standard get() function.

27-33: StringBuilder is a new class for us, its part of Javas Built-In classes. It just acts as a simple way to append each card to a single string. That string is then returned, representing a shuffled deck.

You can then test this out on your own in a main function! First, create an object, print it out. You should get a list of all the cards. At this point, you can shuffle the deck and print it out again, seeing how it works.
This has been immensely long, and we aren't even done yet. Guess that gives me more time to ask you guys to give me any questions you want answered for the summary I'll be doing once this is over!

Oh well, that's it for tonight.Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Tuesday, 27 September 2011

Java: Enumerated Types ( Examples )

So, let's just be lazy and take the example pretty much directly out of the book! Creating bridge hands! (I don't even know how to play bridge).

Statement of Problem

Create a program that builds and prints bridge hands

Design and Implementation

Okay, so we should start with finding out about bridge. Can't write a program about it if we don't understand it! This is applicable to a wider range of things, whether you need to familiarize yourself with a genre of game you're not big on, or gene sequences. You can't just dive into stuff!

Bridge is played with a standard 52-card deck by 4 players. The players sit around a table with sides marked as compass directions (North, East, South, West). Bridge is a clockwise game, so whenever anything is done, its in order of NESW.

Just an aside, I learned this as the order when I was a kid when my South African teacher taught us his method. Never Eat Silk Worms. He also told us Naughty Elephants Spray Water, but the former stuck in my head much more clearly.

Anyway! One person is a dealer for each hand, with the person to the dealer's left shuffling the cards. The person to the right cuts the deck, and then the dealer can deal cards out, 1 at a time in order of rotation.

So we essentially need a way to create 4 hands of 13, then display each hand. Assuming the idea is to have this program evolve into a bridge-playing game, it would be good to think about the grand design. As a list of things we need to worry about, we have the suits and values, each combination of which makes a card, 52 of which make a deck, which itself needs to be shuffled, then distributed 4 ways. Then come the players, who will presumably be named, and are given the cards in rotational order. And further still, is the table, who's organization seems to be important for some reason. Dealer selection if nothing else.

From the above, we see the lowest level of object appears to be a card (Yes, the card has a suit and value, but those aren't entities, they're enumerations). So many cards in a deck, so many cards in a player's hand, what have you. So we need to represent this card, somehow!

Fairly simple as a class. The enums are a little unwieldy, but they're essentially the same as in last post. Each Suit has its own toString() method that returns whatever that suit is, and the same goes for all the values, with Jack returning "J" and so on.

Immediately underneath the enumerators, we have variables that will hold whichever enumeration some instance of the object will have, and these are initialized through the constructor immediately below that. Note that the constructor does take parameters! After the constructor, we have a generalized toString() method, and that just makes it so when you ask for the string representation of an object, it takes both the Suit and Value and squashes them together, as god intended.

Questions? Good, cause now we have a representation of a card, in the next step, I'll be moving on to making a deck of them. Wrap your heads around this first!

That's it for tonight.Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Java: Enumerated Types

Update 1/2 for today. Update 2 auto-posting in like....12 hours.

Very often, we'll want to represent concepts along the lines of "suits in a pack of cards", "days of the week", "pieces in a game of chess". These share something in common, namely that these concepts are types with a small, fixed number of values. (4 suits of cards, 6 types of chess pieces and 7 days of the week). This is the sort of thing described by the term enumerated type. A long time ago (and indeed, how I thought it would be done before reading about it just now), people would represent these types by creating a class for each. Well, no more!

Here's an example of creating an enumerated type for the card types, and writing a toString() method to overwrite the default one:

Click me!
Note the highlighted line, this isn't a class, you cannot instantiate it! We'll look at using an enum class in the next post! Right after you declare the enumerated type, the first part of the body should consist of all those types, separated by a comma. The semicolon denotes the end of the types. Then, we have any methods! You remember switch statements, right? Well, if not, that's okay, tomorrow, we'll be done with the chapter as it appears in the book I'm reading, so it'll be time for a review/summary/whatever. Anyway, while this method works, it kinda doesn't feel so hot. Mostly,I just don't use switch a lot, maybe I'm just not too comfortable around it, even though its way easier. Luckily for me and my silliness, the people developing Java thought to allow each value to define its own methods. This opens up the way for us to do the following: 

This might look a hell of a lot worse, and I can see how. You need to repeat the method name each time, it looks uglier and longer, but keep in mind, you won't always be working with card suits, or toString() functions. The toString() could probably stay as a general method, anyway, but say you had a video-game with several different types of spaceship, you don't want a general function for something that only 1 of them can do, right?

Note that you still need to separate each enumerated type by a comma!

Next post will be largely examples of putting this to use within a class, but first wrap your head around this general idea.

Questions welcome! Comment, follow, subscribe, share etc,

And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Monday, 26 September 2011

Java: Static Variables and Methods

    We know about instance variables and methods. These are the variables and methods that belong to an object, a particular instance of some class. On top of this, Java supports the use of variables and methods that belong to the class as a whole. These are the static ones.

    This class sure is getting used a lot. Here, I've declared a static variable as a counter. Since this belongs to the class and not any particular instance, incrementing it in the constructor increments the count on each new object I create.


Probably could have shown the effect with fewer items, but still. You can see that for each new object we create, the counter increases by 1 on each item. Fun times. Good for keeping track. If count wasn't static, on each object initialization, it would be 0, and you'd get a whole bunch of 1's, which is fairly useless. The general point is, static variables are accessible by any instance of an object, and it changes it for all other instances as well.

    You can have static methods, too, and we see that "main" is one, they more or less aren't used except for main, though, as far as I can tell, but its there if you need it for some reason.

    Tomorrow, I'll do a double update to make up for that missed update a couple nights ago, but for now,
that's it for tonight.Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Sunday, 25 September 2011

Blog Update

Apparently I had captchas on, and just never noticed.
Well they're gone now, fuck 'em.
Post coming later!

Saturday, 24 September 2011

Java: Equality, Null and This

   Thanks for the get-wells, guys, much appreciated. In my fever dreams last night I (no joke) got told to hurry this shit up, and that focusing too much on the details of Java not only retracted from the fun/interest in learning it, but significantly drew out how long it would be to get there. Or, that's how I'm paraphrasing it, there was a lot more swearing, and naked people in the dream. So basically, I'm going to (try to) be less focused on details that are probably of no use/interest to people and focus on being able to write stuff..

    To paraphrase the above, I'm going to try to teach/learn how to drive a car, not be a mechanic.

    I mentioned briefly before that there was an actual difference between using the ".equals()" method and the "==".
    The == operator tests for equality in terms of the representation contained in the 2 variables you're testing. This works fine for primitive types since the variables contain the abstract values, but doing this for objects sucks, since the variables in that case hold references to the objects, not objects themselves. So even if 2 objects were exactly the same, == would come up false.
    In the case of .equals(), it tests for the identity of the object, and Java just kind of assumes every object has this method. If not, a default is provided, which implements identity equality.

    There is a special reference value known as null (null reference). This reference points to no object, nothingness.
A reference variable should point to null when it has no value, and can be explicitly assigned to do so:

    Man, I am using the fuck out of the GenericStack class we were working on. This doesn't work so well for setting primitive types, although any uninitialized variable is set to this value. Doesn't make a whole lot of sense, but fuck it. That's how that works.  But if you try to use an object as if it wasn't a null-type, but it is, you'll get a run-time error. So watch it. The error it comes up with is a NullPointerException, so if you get that you know exactly what it is you're looking for.
    Using null is fun for conditionals and stuff, but the drawback is the amount of extra code and testing you need to do. Still, fun times.

    Every instance method has this local variable automatically declared. "this" is a reference to the specific object the method has been called for. There are 3 main uses for this:

1. It allows a reference to the current object to be passed as a parameter to another method.
    object.someMethod ( this );

2. It can be used when calling other methods, or accessing instance variables on he current object.
    public void someMethod2 ( ) {
        this.someMethod3 ( );
        this.someMethod4 ( this.someVariable );

3.  The third is to use one constructor to call another but really, this gets confusing fast, and I don't see a lot of use for it, at least for small-time programs, so let's gloss over it.

That's it for tonight.Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here (fixed), and feel free to throw loads of criticism at us. 

Friday, 23 September 2011

Surprise (non)Post!

Yay, food poisoning! Sorry guys, but after this short message, I'm out of commission! I'll see if I can make up for lost time later on, though!

I just generally suck at being healthy, and now an external source has got me down again. Fuck yeah.

Thursday, 22 September 2011

Java: Question + Removing Old Objects

    Let's start off today with a question from the comments! (I'm not sure if you guys generally go back to older posts to check them, and wanted to make sure it got answered for you).
Question: Is Java a multipurpose language; ie GUI's, buttons, ect - what are it's main functions besides interactive http - or correct my noobness - maybe give some insight into its major functions, and why Java over other languages? Such as Perl, ect.
     Java has a billion uses, and yes, it has GUI (Graphic user interface) functionality with buttons and the works, separate frames, what have you. This was more or less the last thing I wanted to get into on the subject of Java though, I wanted to focus more on functionality and understanding objects, classes and their relationships to one another, as well as errors and, to a small degree, memory usage. But it will come!
    For interactive http, you're thinking of JavaScript, this is actually a completely separate language to Java, much more simple, much different syntax. I'll also be in the process of learning this. You can actually use some java applets or something in browsers, but I'll just assume you meant JavaScript, 'cause I don't know anything about applets (yet?).
    The main reason to use Java is simply it's power. Object oriented programming is pretty awesome, the use and re-use of certain classes based on context allow for very flexible programs to be made, with few limitations. Compared to some of the other big languages, C and C++ especially, Java holds about the same power with, would you believe it, fewer complexities. The biggest one I can think of right now is pointers. We spoke about these last post, but in C, you actually need to work with the value of the pointer, not just the variable that holds it, and it all gets really messy really quick.
    Another great thing about Java is, since it uses a Virtual Machine (JVM, you might recognize this), it's essentially portable, the program needn't be recompiled to work on each operating system you want it on. AS LONG AS THAT SYSTEM HAS A VIRTUAL MACHINE INSTALLED. This is the primary downside, as far as I can see. Globally usable, but only if you have the (I've been told) bulky JVM on the machine in question. This isn't really a problem in a lot of cases, but still.
    I don't know enough of Perl to comment on why to choose Java over it, unfortunately, but I'm new to everything, so there.

I have adequately answered all your questionsssss

    Onto the actual post! Once an object has outlived its usefulness, there's got to be a way to remove it, to conserve space. If not, then a large program can very easily become overrun with useless information that just bogs it down. An object is considered to be unneeded when there's no variable holding a reference to it, so, when it's unreachable. Luckily, this garbage collection is dealt with by the Java run-time system. So why mention it? Well, garbage collection can happen during the running of the program, but there is no guarantee as to how often this occurs, so an unreachable object could stay in memory for much longer than you might be comfortable with. If your program is small enough, the garbage collection will probably just never occur, but there's not a lot of cases where that'll still be an issue, unless you're running a couple hundred of these small programs at a time.
    A lot f the time, it's possible for an object to be collected without having to worry about it's individual elements/instance variables. If the instance variable references another object, that object will be garbage collected given nothing else refers to it. Yay, chain reactions. But, to allow a programmer some control over object removal, there's a method you can declare in the object's class called "finalize", which is called prior to an objects removal through garbage collection.
    Typically, this method will do all the work required to free resources held by an object that won't be properly managed by the garbage collector. It could be used to close a network connection that would otherwise remain open, or make sure the information in an object is safely written to a file, instead of lost forever. finalize() is an ordinary method in every regard, except for it being automatically called on garbage collection, and as such isn't subject to special rules or regulations like the constructors were.\
Note: use "public void finalize()" as the method signature, or it won't be called!

    Finally, it should be noted that automatic garbage collection does not perform garbage collection or call any finalize methods on termination of the program. While this can't be changed, the ability to ensure everything is properly terminated is important enough to warrant a method to support the behavior. Namely:


....which as you might be able to guess, runs all pending finalize methods. Another useful function you might want is:


...which forces garbage collection to happen right the hell then, instead of having to wait for it. Garbage collection generally makes things a lot easier, since, for the most part, you don't need to worry about details regarding what to delete and when. The penalty we pay for this functionality is a small overhead due to garbage collection taking up system resources, but it's a small price to pay (dun dun duuuun).

That's it for tonight.Questions welcome! Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 

Wednesday, 21 September 2011

Java: Objects & References

    We're now familiar with the idea that (should be) variables act as containers that hold representations of values. Haven't looked into how this principle applies to objects, even though we've been able to use them with no problem. While objects represent actual values, they're not stored inside the variable, but rather, the variable holds a reference. The reference acts as a pointer, or an arrow, telling the program where the object is.
I'm an artist!

    Variables of a class type therefore hold as their representation a reference to the object that's stored elsewhere. We give types to variables to indicate what kind of object they can reference, such as "public int x;" can only reference integers.
    A single object with multiple references to it is said to be shared. This can be a good thing, makes a good program if you can utilize it well, but there is a risk that one part of the program will change a certain part of an object such that it fails in respect to another part of the program. This can be minimized by building the class correctly the first time around to make it hard to misuse etc.

    An important issue for reference variables is that the lifetime of the variable is completely separate to the lifetime of the object it references. So like, even if you're out of scope of some variable that's referencing an object, the object itself still exists.

    Just to recap (because I'm more or less confused at this point.), a primitive-type variable (int, float, char etc) holds a representation of some abstract value, but a variable of some class type (String, ArrayList, what have you) holds a reference (pointer) to the actual object which is stored elsewhere.

I think I earned a short one today, so that's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us. 

Tuesday, 20 September 2011

Java: Object Initialization

    So yesterday we (I) spoke (typed) about overloading, which is, in  a nutshell, having a bunch of methods with the same name take different parameters, so depending on what a user enters for those parameters, the method called differs to accommodate them. Today, we get to talk about initializing objects!

    We know that the correct initialization of variables is a pretty big deal, and this holds true for object initialization, too. Once created, an object needs to be initialized to a known, valid state. Java already makes sure that all an object's instance variables are initialized, but its the programmer's (your) responsibility to make sure the initial state of the object is actually valid with respect to the intended purpose of that object.

    The creation of a new object is a 2-stage process that's triggered by use of the "new" operator, which we've already seen a bunch. 

1. First, memory needs to be allocated for the object (where does it go, otherwise?). This is taken care of by the Java run-time system, though, so not something you need to worry about.

2. Next, the new object needs to be initialized (I'm getting sick of that word, too, don't worry).  This is where all the instance variables of the object are all set to known values, as well as miscellaneous stuff that needs to be taken care for the object to work, such as opening a file.

    During the second step, there're three potential mechanisms for the programmer to use:

1. Direct Instance Variable Initialization
2. Constructors
3. Instance Initializers

And each one gets their own subsection!

Direct Instance Variable Initialization
    Instance variables can be initialized directly, as we're familiar with
Any instance variable declared with an initialization expression is immediately initialized when the new object is created. Simple, but it comes with limitations. Specifically, only a single expression can be used to provide the initial value, and it can't make use of any variables not yet initialized. You can declare an instance variable without it being explicitly initialized, in which care it takes a default value (0 or 0.0 for numerical variables and characters, false for boolean, and for classes, null). As with local variables, explicitly initializing the variable is a good idea, and luckily, direct initialization isn't the only way to do it. An instance variable with no direct initialization can still be explicitly initialized using a constructor.


    A constructor is declared within a class as any other method, but has the specific purpose of initializing the state of a new object. Statements in the method body can assign values to instance variables, create other objects and open files, along with any other operation you might need done. When a constructor terminated, the object should be in a valid state and be ready to use.

    Being a special type of method, a constructor is subject to special rules, the biggest being the constructors name is exactly the name of the class, and doesn't have the preceding return-value attached to it. Example time!

    Note an array list is declared, but not initialized, until we get to the constructor.

    Constructors are pretty cool, they can have actual parameters, so you can control how variables are initialized, and they can be overloaded, which is awesome. In this, they're pretty much methods, without the return value (even though they may as well be void). 
Terminology: A constructor that takes no parameters is called a default constructor.

    Calling a constructor is automatic as part of the "new" operator, and every time you call an object with an empty parameter list, the default constructor is called. This wasn't an issue for us before, despite our lacking constructors, but the Java system will create a default constructor (empty bodied) for us if this is the case, quashing the problem.

Instance Initializers

    There are some cases we can come across where we need a statement sequence to get what we need. We could just put this sequence into a constructor, but this could get annoying if you're overloading them and thus need to repeat the code a bunch of times, so Java gave use this mechanism. An instance initializer associates a block of code directly with a single instance variable. The block is just a compound statement and follows directly after the variable declaration. Here, have another example:

    (Yes, you can call classes within themselves, but that's not important, I'm just lazy).  Look at that. Hell, if you wanted to, you could combine this with instance initialization and have a whole mess of stuff you would probably only find useful in a limited scope. Still, it's there, and therefore good to know about.

That was lengthy. My fingers hurt, so that's it for tonight. Comment, follow, subscribe, share etc, and see you tomorrow!

    And as part of a shameless plug for a friend, if you're interested in classic movies/books/music, visit his site here, and feel free to throw loads of criticism at us.