Showing posts with label Demo Code Project. Show all posts
Showing posts with label Demo Code Project. Show all posts

Friday, March 7, 2014

Using the Random class to generate a random int

Code sample at pastebin


The Random class

java.util.Random
http://docs.oracle.com/javase/7/docs/api/java/util/Random.html

Importing java.util.Random

You will need the following imports statement at the top of your code file:
import java.util.Random;

Generate any random number

Random r = new Random();
r.nextInt();
generates a random number in the int range (-2,147,483,648 to 2,147,484,647).

Generate a random within a maximum range

Random r = new Random();
r.nextInt(max);

generates a random number in the positive int range, inclusive of 0 but exclusive of max.
eg.
r.nextInt(500);
generates a number from 0 to 499. If you want to include 500 in the range, add + 1.

r.nextInt(500 + 1);

Generate a random within a minimum and maximum range

Random r = new Random();
r.nextInt(max - min) + min;

generates a random number in the positive int range, inclusive of min but exclusive of (max - min) and then adds the minimum to correct the range.

eg.
r.nextInt(500 - 300) + 300;

Generates a number from 0 to 299. You can then add your minimum so now the number has the range of 299 to 599. Remember, the actual number will be exclusive of the max so if you want to include the max add + 1.

r.nextInt((500 - 300) + 1) + 300;



Here's a cat.

Friday, September 20, 2013

Simple Frames and Panels

CODE DOWNLOAD - FramesAndPanelsTute.zip

A JFrame is a Window that can contain other GUI components such as JPanel. We can override the JPanel's paint method to force the JPanel to draw the way we would like it to. In the demo code, the final result looks like the following:


In this example, inheritance has been used to extend both the JFrame and the JPanel class. Both of these classes come from the Java Swing library.

Thursday, April 18, 2013

Enum Types

Code Download :: EnumDemo.zip



"Enum Types (The Java™ Tutorials > Learning the Java Language > Classes and Objects)" ( http://bit.ly/15sJydz )

Monday, February 25, 2013

Getting input

DOWNLOAD THE CODE: InputFromScannerPkg

The Scanner class
A class is a template for an object. A class contains methods for performing particular tasks. From one class we can create many object instances.

The Scanner class belongs to the Java library of classes. It contains methods for reading many different types of data, from different types of input.

System.out
You have already seen System.out in action when we print to the console. This is the default stream for output.

This statement causes the words “Print this’ to be printed to the console in Eclipse.

System.out.println(“Print this”);

What you cannot see, however, are the special line ending characters which this method places at the end of the line. When subsequent lines are printed using println(), they each begin on a new line.

Here’s a different way to print to the console:

System.out.print(“Print this”);

Notice that we are now using the print() method. This method does not include special line ending characters. Each subsequent line of characters that is printed using print() will begin immediately where the last line of characters left off.




and the output...


System.in
The following code example uses Scanner’s nextInt() method to read an int input from System.in (default input from console). The input is assigned to the int variable called aNumber.

Scanner myScanner = new Scanner(System.in);
int aNumber = myScanner.nextInt();


Scanner can be told to read different types of data - or tokens. By default, Scanner uses whitespace characters as delimiters of tokens (the characters that separate tokens).

In the case of the nextInt() function, Scanner is using whitespace to delimit tokens, and return the token as an int. (seen in the figure below).

Other Scanner functions of note include:

next() - Return the next token, of any type.
next(String pattern) - the next token is delimited by the pattern supplied as a parameter.
nextLine() - reads the current line and returns it.



and the output...

In the figures above, the user is prompted to enter information. Methods of the scanner class are used to read the input typed into the console, and assign it to variables. The variable values are then printed to the console.

You can read the entire Scanner class specification here:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

Java I/O and Import statements
When we wish to use Scanner:
At the top of the code file we import a reference to the Scanner class by using the line:

import java.util.Scanner;

This line says that we intend to use the class called Scanner from the package called java.util.

In Java, all input and output (I/O) is performed by importing methods from the java.io or java.util packages.

Any source of input or destination of output is called a stream: keyboard, screen, network connection, a file, etc., are all streams.

There are three predefined Streams already open and ready to use in every program:
  •     System.in
  •     System.out
  •     System.err



Object Instantiation
To use the Scanner class, we must first declare an instance of Scanner and give it a name. Similar to declaring a variable in that we declare a type and an identifier. In this case, the type is Scanner.

As well as being declared, an object also needs to be instantiated. The use of the new keyword, instantiates the object called myScanner from the Scanner class.

Scanner myScanner = new Scanner(System.in);

In the next statement, we declare an int variable and assign it the value of the next int that is returned myScanner’s nextInt() function.


int aNumber = myScanner.nextInt();

You will notice that when we instantiated a Scanner object, we have also included System.in, inside of the parenthesis (round brackets). This is an example of passing data to a method. Often, a method needs data passed to it so that it can perform its task.

System.in is the input stream from the keyboard, via the Java console, so, we are telling the Scanner object to use this as its source.

Friday, December 21, 2012

Consider if 2 objects are equal....

Demo Code Project: OverridingEquals.zip

Let's say you have the need to ensure that no 2 objects have the same contents - you want to check if one object is equal to another?

What do you consider equal?

Read on...

equals(Object)
The default implementation of the equals method, provided in all java objects (java.lang.Object) is to compare the memory location of one object, with another.


Consider the example above.

Two objects of type Asteroid1 have been instantiated using identical parameters - both a1 and a2 objects have the same contents. They do not, however, have the same memory location.

When the new operator is used, it causes the system to allocate memory space for the data and as such, a1 and a2 objects have unique memory locations.

When the equals method is used to compare the equality of these 2 objects, the equals method will return false - because each object has a different memory location.

If, for the purposes of your program, you consider that object equality is based on memory location only, the default implementation of the equals method is sufficient.

If however, you consider that object equality is based on the contents of objects themselves (more likely), read on...

overriding equals(Object)

All java objects (java.lang.Object) contain a default implementation of an equals method which compares the memory location of objects to determine equality. When writing your own libraries, you may find that this version of the method is not fit for your purpose. In this case, you can override the method and implement your own version of what you consider to be equality. It is usually the case that object equality relies on comparing the contents of the objects - not the memory locations.

When a class overrides a method, it is providing it's own version of a method that has already been provided by it's parent class (such as java.lang.Object).

You can override the equals method simply by providing your own, in your class. A couple of things to remember though:

The method signature must be the same as the one provided by java.lang.Object:

  • Public
  • Boolean return type
  • method name must be equals
  • takes a single parameter of Object type

...which looks like...



OK, now for the implementation. Our goal is to compare the contents of the object parameter with the contents of the current object.

Here is the definition of the class called Asteroid2:



Note that the equals method has been included in the method list.

The contents of this class are the values for the name, size and rotationRate fields. In our implementation of equals, we will write code which considers equality based upon the values of these fields.

Basically, if the current object has the same name as the parameter object and the current object has the same size as the parameter object and the current object has the same rotationRate as the parameter object, we will consider the current object and the parameter object to be equal.

Here's the code:






The first line ensures that the parameter object (aThat) being passed to the method is of the correct type - in this case Asteroid2. The instanceof operator (compares an object to a specified type) is used to determine the type. The method returns false immediately if this is not found to be true - after all, if the parameter object isn't of type Asteroid2 then it will never be equal to any instance of Asteroid2.

The second line then goes ahead and casts (converts) the parameter object to the type it is being compared to - in this case, Asteroid2. Once the cast has taken place, we can then treat the parameter object (aThat) as an instance of Asteroid2 (That) and call each of it's methods to begin determining equality.

The return statement uses the logical operator && to join together a number of expressions, relating to the fields on the objects, which will ultimately evaluate to true or false.

Once again...basically, if the current object has the same name as the parameter object and the current object has the same size as the parameter object and the current object has the same rotationRate as the parameter object, the method will return true.

Calling the equals method
Let's assume that we wish to add a new Asteroid2 object to an existing ArrayList of Asteroid2 objects but we want to make sure that an object with the same contents does not already exist in the ArrayList.

The example below uses a loop to compare the new Asteroid2 object with each object in the ArrayList:


Because the Asteroid2 class has overriden equals, we can be assured that only objects containing unique contents will be added to the ArrayList.

Incidentally, the ArrayList has a contains method which evaluates object equality in the same way - dispensing with the need for a loop. It simply calls the equals method on each object in the ArrayList - equality is based on whether the method has been overriden by the class in question (contents) or not (memory location).

One last thing...

We can also quickly return from the equals method by checking if the parameter object has the same memory location (and hence is the *same* object) as the current object.


When the equal to operator (==) is used on objects (reference types), the references (memory locations) are compared.

see also:

"Object (Java Platform SE 7 )" ( http://bit.ly/YrEmpk )

"Overriding and Hiding Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance)" ( http://bit.ly/Zn8eop )


Sunday, September 16, 2012

Casting


DOWNLOAD CODE PROJECT: Casting

Casting can be used to convert an object of one class type to another, within an inheritance hierarchy.

For instance, all Java objects inherit from the Object class. A class called Player may be implicitly cast into the type Object, as below:

Object o = New Player();

However, the following statement will not compile:

Player P = o;

This is because a Player object is always an instance of Object whereas an Object is not always an instance of Player (An Object is alllll kinds of things).

We need to tell the compiler that o is an instance of Player, as below:

Player P = (Player) o;

This is called explicit casting - or down casting. Note that the type we are casting to is included in the parentheses.

The Animal family
Consider a family of classes where Animal is the superclass and it has sub classes of Mammal and Fish. In this scenario, Animal is the generalisation and Mammal & Fish are the specialisation.



We could, for instance, create an ArrayList to store all types of Animal, as below:

ArrayList<Animal> animalList = new ArrayList<Animal>();

and to that list we could add any type of animal:

animalList.add(New Mammal());
animalList.add(New Fish());

When the Mammal & Fish object types are added to the ArrayList, they have been implicitly cast as Animal. This means that they may only be used in the context of Animal - only state and behaviour belonging to Animal will be accessible from theses objects (even though we can see their actual type, on the screen in front of us).

If we wish to use these objects as their specialised type, we must first discover their run time instance type and then use explicit casting - down casting, to convert.

Consider the following inheritance hierarchy:



(NOTE: The diagram shows the hierarchy incorrectly - Mammal and Fish should be swapped :P)

There are now 7 types of Animal and we have instantiated each type into the ArrayList, as below:

ArrayList<Animal> animalList = new ArrayList<Animal>();
animalList.add(New Animal());
animalList.add(New Mammal());
animalList.add(New Fish());
animalList.add(New Bass());
animalList.add(New Snapper());
animalList.add(New Wombat());
animalList.add(New Kangaroo());


Let's say we want to search the list for certain types of Animal - remember, currently the compiler sees them all as the generalised type - Animal, because that is the type of the ArrayList. 

We could look for specific types, such as Bass. Or we could look for types of specialised type - for instance, finding all types of Fish.

Getting the specific type - equals
In the example below, a loop is used to traverse the list of Animal, looking for objects of the specialised type Bass. 

The equals() comparison method is used on each object to evaluate whether it's run time class is equal to Bass.


Note the statement:


The getClass() method returns the run time class of the object. The equals() method then compares that type to the type mentioned in the parentheses. In this case, Bass.

In the next statement, if the evaluation is true (if the currentAnimal object was found to be of type Bass), the Animal object (currentAnimal) is explicitly cast to an object of type Bass (bass).



The bass object now has the context of Bass, meaning that it may access all state & behaviour of Bass, as well as Fish, as well as Animal.

Getting types of specialised type: instanceof operator
In the example below, a loop is used to traverse the list of Animal, looking for any objects which are types of Fish. Remember, Fish, as well as being a subclass of Animal, is also a superclass of Bass and Snapper.

The instanceof operator is used on each object to evaluate whether it's run time instance type is equal to Fish.



Note the statement:


The instanceof operator determines if the currentAnimal object is an instance of Fish, regardless of whether it's specific type if Bass or Snapper. This means that all objects of type Fish, Bass and Snapper will be discovered using this method.

In the next statement, if the evaluation is true (if the currentAnimal object was found to be an instance of Fish), the Animal object (currentAnimal) is explicitly cast to an object of type Fish (f).



The f object now has the context of Fish, meaning that it may access all state & behaviour of Fish, as well as Animal.


Monday, June 11, 2012

String trim()

DOWNLOAD THE CODE: TrimmingWhitespace

The Java Character class defines whitespace as one of a few different types of characters, including the space character & a carriage return character.

The String class contains a trim() function which removes leading & trailing (at the beginning and at the end) whitespace.

For example, if we are reading a text file using Scanner, with a semi-colon as the delimiter, we only want to read the meaningful part of the string. Carriage returns should be discarded.

For our examples, we will use the following text file nums.txt. See screenshot below:



The code example below reads nums.txt, inside of a while loop.The semi-colon is used as the Scanner's delimiter. Each token in the string ends with a semi-colon and the next begins immediately after the semi-colon. This means that any carriage return characters may be included in the token. This is not ideal and will produce the following result:


Here is the output:


Note that the carriage return separating the lines between the tokens "five" and "six" has been read and rendered.

Using trim()
In the example below, we will trim() each token so that any whitespace such as carriage return characters are discarded.


Here is the output:




Sunday, June 3, 2012

if then else statements

DOWNLOAD THE CODE: UsingIfThenElse.zip

<<< back to if statements

In the previous post on if statements, we saw how we could use an if statement to detect if a condition was true and then execute statements accordingly. An if-then-else statement allows us to branch off in multiple directions.

The example below determines if the user has entered an age that is equal to or greater than 18. If this condition evaluates to true, the user receives the message "You are 18 or over". If the age is anything else, the user receives the message "You are less than 18".



Here's the output:




In the next example, we have multiple if's to determine the entered age:


Note that each if section is contained within curly braces.

Here is the output:





also see:
also see:
"The if-then and if-then-else Statements (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/zflbUx )

The concatenation operator

DOWNLOAD THE CODE: ConcatPkg

The concatenation operator is the addition symbol +.

Concatenation is the act of joining multiple values together to form a single String.


Here's the output:


Note! The addition symbol is also used as the addition operator! If the addition symbol is placed between 2 numbers, it will treat the expression as an addition expression!

Saturday, June 2, 2012

Switch

CODE DOWNLOAD: UsingSwitch.zip


A Switch can be used to evaluate a number of numeric types such as byte, short, char & int.

Let's say you want to check the value of a single variable and based on this value, one of many things may happen.

In the example below, the user enters a number. This number is then checked by the switch. The first case to match, executes a statement - in this case, printing a message to let the user know what the entered value was.


If the user entered a value not listed in the cases, the default section executes. It is good practice to always include a default case in your switch.

Notice that the final statement in each case is break. This causes the switch to stop checking down the list.

We can also execute a common statement for multiple cases, as in the example below:


Of course, we could use a number of if then else statements to achieve the same result, however, as we are only checking the value of a single variable, the switch is a more elegant and readable solution (subjective).

Here's a cat:




"The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)" ( http://bit.ly/y2TVYE )

Monday, May 28, 2012

PrintWriter


DOWNLOAD THE CODE: PrintToFile.java

The PrintWriter class contains 2 very useful methods:
  • print(String)
  • println(String)
These methods write a String to a file.
The println method adds the end-of-line character after the string.

The constructor of the PrintWriter class accepts a file to write to. As such, a File object has been declared. The constructor of the File object accepts a String file path of the file's location. It is interesting to note that if the file has not already been created, the PrintWriter will create it automatically.

The example below contains 2 loops. The first loop writes the numbers 1-10 (using the loop counter) to data.txt using the print() method. As such, each number is written immediately after the last. The second loop also writes the numbers 1-10 to data.txt but uses the println() method so that each number is written on a new line.


Here is the output:




Throws FileNotFoundException. If you do not implement exception handling for this exception, the compiler will force you to rethrow it.

And if you want to read text file from a file, here's a post about the Scanner class.

"PrintWriter (Java Platform SE 7 )" ( http://bit.ly/LsOVki )

Here's a cat:


Sunday, May 27, 2012

While loop

DOWNLOAD THE CODE: usingWhileLoops.java.zip

While is a type of loop. Statements inside of the loop will continue to repeat while the loop condition is true.

The while loop is primed with a boolean expression/condition. When the condition becomes false, the loop will stop.

while (condition) {
    // statements to loop.
}


The example below uses a while loop to increment the value of the int variable num. On each pass of the loop, num has 100 added to it. The loop will continue to execute while the value of num is less than or equal to the value of the int variable maxnum.


The output:


The loop condition can be any expression that return a boolean value.


"Java For Complete Beginners - while loops" ( http://bit.ly/JGnAII )

What is a Constant? Final keyword

DOWNLOAD THE CODE: FinalValuePkg

We can store a value in a constant. Very similar to a variable except that a constant has a constant value. That is, the stored value is never changed as a result of processing.

Constants are used where a value should never be changed such as a maximum, minimum, number of hours in a day, days in a week, etc.

A constant begins with the keyword final. Just as with a variable, a type & identifier must be given.


The compiler will not allow any processing statements to change the values of these constants.


UML Class Diagram Notation
The UML Class Diagram notation for a constant (final) is as below:



CIRCLE_WIDTH and CIRCLE_HEIGHT are defined using uppercase and have each been assigned a value.

"Java Syntax: Declaring and Using Constants in Java" ( http://bit.ly/JmgF5S )

Here's a cat:


Wednesday, May 23, 2012

The split function

DOWNLOAD THE CODE: usingSplit.java.zip

The String class contains a split() function. This means that any single string may be split into several substrings, based upon a nominated delimiter character. split() returns an array of String, containing each substring.

Example 1: split a string using a space as the delimiter:

Output:



Example 2: split a string using a comma (,) as the delimiter:

Output:





Monday, May 21, 2012

Scanner class - Part 2.

DOWNLOAD THE CODE: Scanner.zip

<< Continued from part 1

In the next example, we will nominate a character to use as a delineation token - the semi-colon (;).

Below is the text file shoppinglist2.txt. Note that each line contains a semi-colon. Now, rather than defaulting to whitespace as the delineation token, the Scanner will look for the semi-colon character.


Here's the code:



Note that the Scanner's property useDelimiter has been set to use the semi-colon (;). Each token is now measured by the presence of a semi-colon.

Here's the result: