GPT Chatz - Get Paid to Post Forum

Full Version: Introduction to Java Programming
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
Here is a bunch of notes I used during my university career to help me learn about JAVA programming. Very simple to understand =)
THIS IS NOT COPY AND PASTED. The only parts that are is the code JAVA codes. Everything else here was hand written during class and I had been typing this for DAYS.

JAVA-001: Beginning JAVA

Applets and IDE


JAVA allows use to write two kinds of programs:
  • Applications -- Designed to run by double-clicking the icon for them on the desktop
  • Applets -- Designed to run as part of an Internet delivered service such as a web-page or Internet Commerce system.


Here is an example of an Applet:

Code:
import java.awt.*;
import javax.swing.*;

public class DemoApplet extends JApplet {
    public void init () {
        JRootPane rootPane = this.getRootPane();
        rootPane.putClientProperty(
            "defeatSystemEventQueueCheck",  Boolean.TRUE);
        }
    public void paint (Graphics g) {
        setBackground(Color.blue);

        g.setColor(Color.white);
        g.drawString("This is a simple JAVA program", 50, 50);
        g.drawString("It's pretty silly, isn't it?", 50, 100);
        }
    }

Here are some definitions of the given code above:

Importing the required components
Code:
import java.awt.*;
import javax.swing.*;

Brings in the Graphics & display components that allow us to develop Applets and Applications

Class Header

Code:
public class DemoApplet extends JApplet {
  • Every program is built in a component called a ‘class’. The class is the container that holds everything needed to run the program.
  • Called DemoApplet
  • extends JApplet means that we are creating a JApplet and want to use the standard pieces of the Japplet
  • public means that the browser is allowed to run it (Part of JAVA security)
  • { indicates that program instructions follow. Must match with a } elsewhere in the program


Method init:

Code:
public void init () {

The init method is called as soon as the browser starts your applet. It’s where you set things up. { Starts the instructions for the method init
We’ll need a } to end it later.

Init method code:

Code:
    JRootPane rootPane = this.getRootPane();
            rootPane.putClientProperty(
        "defeatSystemEventQueueCheck", Boolean.TRUE);
    }

Sets up the event handling queues on older browsers.

paint Method Header(By far one of my favorites)

Code:
    public void paint (Graphics g) {

This method is used to draw things to the screen. ‘g’ is the Graphics object we’re going to use to tell the system what to display.

paint Method body

Code:
setBackground(Color.blue);
An instruction to the Applet itself to make the background blue
Code:
g.setColor(Color.white);
Changes the text and drawing color to white
Read as “g, set the color to white.”
Code:
g.drawString("This is a simple JAVA program", 50, 60);
Draws a string (a bunch of characters) at location 50, 60. 50 pixels over and 60 lines down from upper left corner
This is a simple JAVA program -> The text output is surrounded by double quotes (“)

An IDE is an Integrated Development Environment
An editor (for entering and fixing the programs)
A compiler (to convert the JAVA into a runnable program)
A run time environment (to run the resulting program)

The IDEs I have worked with are called BlueJ and Eclipse.
JAVA-002: Beginning JAVA
Applications & IDEs


The Application

Code:
public class DemoApplication {
    static public void main () {        
        System.out.println("Applications don't … “);
        System.out.println("So we're going to … “);    
        System.out.println("To the console display");
        }
    }

Class Header

Code:
    public class DemoApplication {

Notice: No extends Japplet this time

Main method header

Code:
    static public void main () {

static is required. It means that the code doesn’t need to be set up by a browser like an applet. Must be called main or the system can’t find it.

Now here are some explanations of the code:

Code:
System.out.println (“ …. “);
Displays the string in the double quotes to the terminal console window
Console usually only used for error messages
After the text is displayed, the output is automatically advanced to the next line.
Code:
System.out.print (“ … “);
Doesn’t go to the next line after the text is output.

Lastly, Don’t create an Applet class just a normal class

JAVA-004: Global vs. Local

Instance Variables, Method Variables and Masking


Instance Variables:

Created just under the class header.
Available in every method in the class: Unless masked by a local variable
Code:
public class Example {
    int eggCount;  // This is an instance variable

Local Variables
Created inside a method
Available ONLY inside the method: These mask (hide) the instance variables if they have the same name.
Value disappears when method is finished

Code:
public void paint (Graphics g) {
    int eggCount; // This is a local variable

Example:
Code:
public class IterativePCodeApplet extends JApplet {
      int currentProblem, currentState, outputLine, pgmLine;
    double value;

    public void init() {
        int answer;
        }
    private void setUpSolution() {
        String value;
        }
    private void handleInput(int value) {
        String answer;
        double total;
        }
    }

Instance Variables
Code:
public class IterativePCodeApplet extends JApplet {
      int currentProblem, currentState, outputLine, pgmLine;
    double value;

currentProblem
currentState
outputLine
pgmLine
value

Init Method

Code:
public void init() {
        int answer;
        }

Local: Answer
Instance: currentProblem, currentState, outputLine pgmLine, value

setUpSolution Method

Code:
private void setUpSolution() {
        String value;
        }
Local: value
Instance: currentProblem, currentState ,outputLine ,pgmLine,
value (masked by local variable)


HandleIntput method

Code:
private void handleInput(int value) {
        String answer;
        double total;
        }
Local:
value (parameter), answer, total,
Instance: currentProblem, currentState, outputLine, pgmLine, value (masked by parameter)

Independence of Local Variables
Each method has its own local variables
Even if you use the same name!
Prevents one method from accidentally changing a value for another one
Good idea to have only those variables that must be shared as instance
Everything else local

Common Bug
Code:
public class Demo {
       String value;
       public void init () {
              String value = “This is a value”;
       }
       public void paint (Graphics g) {
              g.drawString (value, 100, 100);
       }
}
What is output?

JAVA-005: Data Types

Primitive Data Types
Declaring Variables


Basic Types:
Have to tell JAVA what kind of information each variable is to handle
Primitive types: Types that the computer handles directly in the hardware.
Three kinds: character, integer and floating point

char:
Size is 16 bits
Holds a single Unicode-16 character
DOES NOT hold a whole String (a name for instance)

Integer Type:
byte: 8, -128-127
short: 16, -32,768 to 32,768
int: 32, -2,147,483,648 to 2,147,483,647
long: 64, -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float: 32, 6 digits, exponent is -38 to 37
double: 64, 14 digits, exponent is -145 to 144

Declarations

Code:
double radius;
double height;

OR

Code:
double radius, height;

Instances VS Local
Decide on whether the value is needed everywhere or just within a single method.
Instance variables for the values needed everywhere
Local variables for values only needed in a single method

Cookie Tin Problem
Create a program that calculates the volume and area of a cookie tin.
Need radius and height to calculate
Values needed throughout program -- make instance variables

Try this out!!!!!!!!!!!!!!!!!!!!!!!!!!!

Here is the stub program
Code:
import java.awt.*;
import javax.swing.*;

public class CookieTin extends JApplet {
    double radius, height;

    public void init() {}
    public void paint(Graphics g) {}
    }

JAVA-006: Assignment Statements

Calculations in Java


Assignment statements:
<Variable> = <Calculation>;
Always put variable that holds the answer on the left hand side
Always end with a semi-colon

Assigning Values
In our cookie tin problem, we would want to assign values to hieght and radius:

height = 10.0;
radius = 5.0;

Since output is in paint and init is a good place to initialize variables, these had best be instance variables

Calculations
In paint in the Cookie Tin problem.
Anywhere they are needed in general

Code:
volume = 3.14159265358979 * radius * radius * height;
area = 2 * 3.14159265358979 * radius * height + 2 * 3.14159265358979 * radius * radius;

Notes:
Variable that holds the result is always on the left hand side
No exponentiation in JAVA
Use repeated multiplies
class Math has exponentiation -- next section
Writing out PI this way is too much typing

Constant Values:
We can deal with PI problem by declaring a constant.
Under the class header

private static final double PI = 3.14159265358979;

Differences between private, static, and final
Only this class can use the value
Part of JAVA’s data security.
More later in the course
Static variables are stored so that there is only one version of the constant no matter how many times we use the class
Final means that the value can’t be changed by our program later
PI = PI + 1.0; // Illegal

Constants
Code:
volume = PI * radius * radius * height;
area = 2.0 * PI * radius * height + 2.0 * PI * radius * radius;

This is a lot shorter
Note: 2.0 isn’t needed but a good idea to mark floating point constants

Local Variables
Volume and area aren’t needed globally
Only by paint method
Make them local to paint

Code:
public void paint (Graphics g) {
    double volume, area;

Output of Variables
JAVA has no drawDouble or drawInt method for output
When you add a numeric variable to a String, JAVA converts numeric value to String
Can use drawString

Code:
g.drawString ("Volume = " + volume, 50, 50);
g.drawString ("Area = " + area, 50, 100);

Completed Paint Method
Code:
public void paint (Graphics g) {
      double volume, area;
      
      volume = PI * radius * radius * height;
      area = 2 * PI * radius * height +
        2 * PI * radius * radius;
      
      g.drawString ("Volume = " + volume, 50, 50);
      g.drawString ("Area = " + area, 50, 100);
      }
Operators:
+ = addition
- = subtraction
* = multiplication
/ = division

Precedence of operators:
Brackets
Unary minus (like -total).
Multiplication (*), division (/) and modulus (%)
Modulus is the name Computer Science gives to the remainder after integer division.
17 % 10 = 7 because 17 divided by 10 is 1 with 7 remainder
When there are more than one *, / or % in a calculation, they are evaluated from left to right.
Addition (+) and subtraction (-)
Left to right again if more than a single operator

Example:
D = A * B + C / E
A * B First
C / E Second
Addition Last

D = -A * ( B + C / E )
Unary Minus
Brackets
C / E
Addition
Multiply Last

Completed Cookie Tin problem
Code:
import java.awt.*;
import javax.swing.*;

public class CookieTin extends JApplet {
      double radius, height;

    public void init() {
        height = 10.0;
        radius = 5.0;
        }
      public void paint(Graphics g) {
            double volume, area;

        volume = PI * radius * radius * height;
        area = 2 * PI * radius * height + 2 * PI * radius * radius;

        g.drawString ("Volume = " + volume, 50, 50);
        g.drawString ("Area = " + area, 50, 100);
        }
      }
Converting double into int
Round a value to the nearest whole number.
type coercion or type casting

int nearestInteger = (int)(0.5 + myDoubleValue);

(int) is doing the conversion from double to int.
Discards the fraction (doesn’t round).
Add 0.5 first.
3.4999999.
Needs to be rounded down.
Add 0.5, getting 3.9999999.
(int) throws away the fraction - the 0.999999 part - leaving us with just the 3.
3.5.
Need to round up.
Add 0.5, we'll end up with 4.0.
(int) throws away the .0 leaving us with just the 4.

JAVA-008: class Math
Programs need special functions:
sine, cosine, tangent, etc.
Could write
Would be a cumbersome
JAVA has bundled into a class called Math.

Example
Range = (cos(Angle) * sin(Angle) * V * V) / 20

Math class like this:
Code:
range = (Math.cos(angle) * Math.sin(angle)
                * v * v) / 20.0;

Angles
All angles in Math class are in radians
Code:
Math.toRadians(angle))
Changes an angle in degrees to one in radians.
Code:
Math.toDegrees(angle))
changes radians to degrees, too.
A very accurate version of PI.
Code:
Math.PI

toRadians
To use degrees instead of radians:
Code:
range = (Math.cos(Math.toRadians(angle)) * Math.sin(math.toRadians(angle)) * v * v) / 20.0;
OR
Code:
double radians = Math.toRadians(angle);
range = (Math.cos(radians) * Math.sin(radians) * v * v) / 20.0;
Check this out: What more can math do?
URL on java.sun.com:

http://java.sun.com/j2se/1.5.0/docs/api/...Math.html.

Note: Different log base:
Math.ln(x) / Math.ln(New Base)

JAVA-008: Java Shortcuts
Shortcut
Used often so special shortcuts in our assignment statements.
More efficient
Increment: Add one to a variable.
Code:
x++;
Decrement: Subtract one from a variable.
Code:
x--;
Running Addition: Add value to variable
Code:
total += value;
Running Subtraction: Subtract value from variable
Code:
total -= value;
Running Multiplication: Multiply variable by a value:
Code:
total *= value;
Running Division: Divide variable by a value
Code:
total /= value;
Running Modulus: Make variable the modulus of the variable and a value
Code:
total %= value;

Objects
New programs have common pieces:
-Programs we've written in the past
-Programs other people have written.
-Pieces in program similar to each other.
Could write everything ourselves:
-Copying code as needed.
-Wasted time and having to find problems several times (once in each copy we create).
Use object oriented programming:
-Design and implementing classes (blueprints)
-Method we are going to be using in this course.

JAVA-009 OOP
JAVA is object-oriented programming language.
-Creates source code file called a Class.
-Class is a blueprint for all objects of that Class.
--Contains the instance or attribute variables
--Program code necessary to make the Class work.
---Called methods.
---Used methods in Graphics object g to draw
--Used as blueprints to create working pieces that are 'components' to make our program work.
--instantiate (create) actual program objects from Class

IsA and HasA Relationships
Everything related to everything else.
Biology illustrates.
A pair of dogs: Fifi and Chomper.

Comments
Not too much alike do they?
Have tails, teeth, have noses, have four legs, warm blood, ears, eyes and fur.
Called "attributes"
Tells us both are "Dogs".

IsA
Fifi IsA Dog
Growler IsA Dog

Indicates first part (Fifi or Growler) is a unique instance of the generic type (the Dog).

In programs
Draw IsA relationship as an arrow from the "child" to the "parent".
Dog -> Fifi
-> Chomper

Attributes and HasA
Fifi and Chomper have same attributes:
-master, tails, teeth, nursing, legs, warm blood, ears, eyes and fur
-Actual details vary though
--Color of the fur is different between our two Dogs
--Indication attributes belong parent "Dog" and not to Fifi or Chomper

Class Dog and HasA
All Dogs have masters, tails, teeth, nose, legs, warm blood, ears, eyes and fur.
HasA relationship.
Dog HasA teeth
Dog HasA legs

Instances and Instance Variables
Fifi and Growler are "instances" of the Dog.
-Dog provides the blueprint
-Fifi and Growler produced from "Dog" blueprint.
-Each Dog inherits attributes of class
--Has its own copy of them.
--Each features is called an attribute
--Stored in an instance variable
---Each instance gets its own copy

Cats in the Hierarchy
Add another creature - a Cat called "Cat".
-A lot of the attributes of a Dog:
-teeth, nose, legs, warm blood, ears, eyes and fur
-Also has claws
It isn't a Dog.
-Need a new Class called "Cat".

Shared information
Cats and Dogs share a great deal of information.
-Both are Mammals.
Cat will have no master like the Dog class does.
Attributes for Mammal have those attributes that all Mammals share:
-teeth, nose, legs, warm blood, ears, eyes and fur.
Dog has own attribute: master.
Cat has own attribute: claws.
Class Hierarchy
Cat <- Mammals -> Dog
^---------------------^---^
Blue------------------Fifi--Chomper

Inheritance
Fifi, an instance of Dog, is also an instance of Mammal.
-Fifi inherits all of the attributes of Mammal through its own parent, the Dog.
-Things built for Mammal are in Dog and also in Fifi.

Creating and Using Objects
We’ll use them before we get into creating our own Classes and objects
We need to look at:
1.How they are created
2.How they work
3.What they look like in JAVA.

Creating objects from Classes
fifi = new Dog("Fifi");
growler = new Dog("Growler");

new
used to create a new object.
“instantiation”

AnimalLib’s Dog class creator method:


public Dog (String name) {
This method:
Needs a String
-text enclosed in quotes
-Used to give the dog a name by enclosing the name in quotes.
-String is one of Java's builtin classes,
-Must be:
--"Fifi", "Growler" and "Blue".
--Case is critical
-Handles aren't the objects.
--Give us access to the instance we create with new.


Talking to animals
How would you order the dog if you have more than one dog.
Mention the dog by name and then tell it what to do:

"Fifi, chase a car”
"Growler, chase Cat”
"Fifi, bark".

Doing Actions
To tell the object fifi to bark, we'd write:

Code:
            fifi.bark();

To tell the object chomper to chase fifi, we'd write:

Code:
            chomper.chase(fifi);

[size=largeThe "."[/size]
The dot (".") is very important.
Links the object to the method in class.

Code:
        fifi.bark();

Says: "Fifi, I want you to bark”

Code:
        chomper.chase(fifi);

Says "Chomper, I want you to chase Fifi".

AnimalLib Classes
AnimalLib:
-A collection of images and classes that work with Cat, Fifi and Chomper.
-Get the ZIP archive of these by downloading AnimalLib.zip.
-Create a JApplet and then return to your desktop.
-Copy the contents of the AnimalLib archive into the project folder:
--Dog.class
--Cat.class
--Animal.class
--Action.class
--Street.class
--A folder called Animations.

In Java
We need some means of creating objects from our Dog class
-Class Dog isn't a Dog it's only the plans for a Dog.
-Difference between blueprints for house and house itself.
-You can create any number of houses using the same blueprint.
-Can create any number of instances of a class from that same class.
-Real house has a location (it's address),
-Handle in our program for each instance we create

Dog fifi, growler;

Where do they go?
Need to be available to all our methods?
-Make instance variables
Could be local to a method
-paint or init
These handles don't make the Dogs only create a handle attached to new Dog when created
Two Dog handles
-fifi and growler

Handles to our Objects
Needs:
-A Street object (for our animals to play on)
-Two Dog objects (one for each Dog)
-Single Cat object.

Code:
public class ExampleApplet extends JApplet {

    Street street;
    Dog bigDog, smallDog;
    Cat cat;

nit method
Animal objects are all instance variables
-Available throughout the ExampleApplet.
Use init to create our objects and set things up so that we can get something to happen.

Code:
            public void init() {

Street Play on:
Need to create is the Street for them to play on.
-Creator method for Street needs the Applet that is creating the Street as a parameter.
-‘this’ in JAVA refers to the current object.


Code:
        street = new Street(this);

Creating the animals
Three animals:
-bigDog(for Fifi)
-littleDog (for Growler)
-cat (for Cat).
Add each to the street after we create it.
Street has method called 'add'.
-Used to add an Animal to the Street
Code:
        bigDog = new Dog("Fifi");
        street.add(bigDog);


        smallDog = new Dog("Growler");
        street.add(smallDog);


        cat = new Cat("Cat");
        street.add(cat);


What does it mean
Make bigDog the new Dog whose name is "Fifi"
Street, add bigDog
Make smallDog the new Dog whose name is "Growler"
Street, add smallDog
Make cat the new Cat whose name is "Cat"
Street, add cat

The Street init Method
Must tell our Applet about the Street and all the critters that we've added to the Street.
JApplets use contentPane.
-Part of Swing
-These display everything and do input, too.

getContentPane returns the handle to the contentPane.

Code:
getContentPane().add(street);

Cascade
Notice that the output of the first method (getContentPane) is an object
-Used by second method (add).
-Called a cascade
-Often used Object-Oriented Programming.
Where’s the JApplet object?
-JAVA shortcut. If you don't mention an object, JAVA assumes you mean the current one.
Could be written as:


Code:
        this.getContentPane().add(street);

Applet Screen size init method:
Good idea ensure JApplet has correct size or some of action make take place off screen and be invisible.


Code:
setSize(708, 338);

init Method:Action
Want to make our three animals bark or meow, have Fifi chase Growler and walk over to location 250 on the street. We'd put this in init as well:

Code:
bigDog.barks();
        smallDog.barks();
        cat.meows();
        bigDog.chases(smallDog);
        bigDog.walksTo(250);
        }

Paint Method
Code:
public void paint(Graphics g) {
    street.paint(g);
    }

Animal library classes
Three classes that you will use in AnimalLib
-class Street
-class Dog
-class Cat

Class Street
Code:
public Street(JApplet applet)
public Component add(java.awt.Component c)

Creator method


Code:
public Street(JApplet applet)

creates a new Street for the JApplet passed as a parameter
Parameter: applet - Applet this Street is being created for
Returns created Street
Code:
public Component add(java.awt.Component c)
Adds a Component to the Street for animation
Parameter: c - Component to add to the Street
Returns c

Class Dog
Code:
public Dog(String name)
public void barks()
public void chases (Animal target)
public void walksTo (int x)

Creator method
Code:
public Dog(String name)
creates a new Dog with the name passed as a parameter
Parameter: name - Name of the Dog
Returns created Dog

Code:
public void barks()
Makes the Dog bark

Code:
public void chases (Animal target)
makes the Dog chase another animal
Parameter: target - Target animal to chase

Code:
public void walksTo (int x)
makes the Dog walk to another screen location
Parameter: x - Screen location to walk to


Class Cat
Code:
public Cat(String name)
public void meows()
public void chases (Animal target)
public void walksTo (int x)

Creator method:

Code:
public Cat(String name)
Creates a new Cat with the name passed as a parameter
Parameter: name - Name of the Cat
Returns created Cat

Code:
public void meows()
Makes the Cat meow

Code:
public void chases (Animal target)
Makes the Cat chase another animal
Parameter: target - Target animal to chase

Code:
public void walksTo (int x)
makes the Cat walk to another screen location
Parameter: x - Screen location to walk to

JAVA-010: class String
Text Handling


Class String
Most programs need strings of characters.
Primitive 'char' holds a single character
Not enough for a person's name, address or eMail address.

Creation
Like every object in JAVA, class String has a creator method

Standard Form:
Code:
            String name = new String("Attila the Hun");
This is cumbersome.
Shortened version:
Code:
            String name = "Attila the Hun";

The process
Creates a string
-Puts characters: Attila the Hun.
-Quotes are stripped off.
-Delimiters for the string
--Where the String starts and stops.
-Escape characters:
--If you want a quote \" is a single character String that contains only one double quote(").

Concatenation
Strings created by concatenating a String to primitive type.
Total is type int

Code:
        String answer = total + "";


Joining Strings
Concatenation is the method that adds one String to another String to create a third String.

Code:
    String title, firstName, lastName;

    title = "Sir ";
    firstName = "Isaac ";
     lastName = "Newton";
Concat Method
Code:
public String concat(String)

Using concat, we could write:

Code:
    String partial = title.concat(firstName);
    String fullName = partial.concat(lastName);

Method cascade:

Code:
    String fullName = title.concat(firstName).concat(lastName);

How this is working
The string title (“Sir ”) is concatenated with the String firstName (“Isaac ”).
This creates a temporary String (“Sir Isaac “)
Temporary String concatenated with lastName (“Newton” to produce the desired String.
Stored in the string fullName (“Sir Isaac Newton”)


The + Operator
Using + operator, we could write:

Code:
String partial = title + firstName; String fullName = partial + lastName;

All in one line:

Code:
    String fullName = title + firstName + lastName;


String searching
indexOf
Search from the start of the String

Code:
        int indexOf(String search)

Search starting at some arbitrary location in the middle of the String

Code:
        int indexOf(int start, String search)

It allows us to search one String for a second String. Suppose we have a collection of data separated by commas:

Code:
        String data = "first,second,third";

Don’t know where the commas were in general
We'd need to find the commas.

int locn = data.indexOf(",");


String ‘data’ searched from the beginning for the first occurance of the String ",".
Returns the location in the String if found
Returns negative number if not found

Searches the string from location 0 until comma at location 5.
Returns value as an int and the 5 would be stored in the int variable locn.

Searching for the 2nd comma
Need to start searching after the first comma.
IndexOf needs number that is starting location for the search:
locn contains 5
Can’t start at 5
indexOf would find same comma and quit.
Start one place farther up:


Code:
int locn2 = data.indexOf(",", locn+1);

Searching for the Third cmma
Starting at location 6 (i.e. locn+1 is 6),
indexOf goes to location 12.
This returned and locn2 would end up with the value of 12.

Overload Methods
A method with many different actions and sets of parameters,
Used to deal with a variety of situations and different kinds of data.

SubStrings
Now that we've found the commas, we're going to want to pull apart the data string into three pieces: the part ahead of the first comma, the piece between the commas and the part after the last comma.
Called a substring.

Code:
        public String substring (int, int)
        public String substring(int)
First Form:
The two parameters are start location for the substring
Location just past the last character we want in our substring


Code:
String firstPart = data.substring(0, locn);

First part SubString
locn contains 5 from our use of indexOf.
Substring then creates a new String containing characters at 0, 1, 2, 3 and 4.
Character 5 (the comma) is ignored
Code:
            firstPart = “First”

Second part Substring
String secondPart = data.substring (locn + 1, locn2);
Start at locn + 1.
One character past the comma

Code:
    secondPart = "second"

Third Part
The last piece has only a starting point.
Everything after our second comma to the end of the string.

Code:
String thirdPart = data.substring (locn2 + 1);

thirdPart = "third"

Length of a String
Returns how many characters are in a String.

Code:
public int length().

To find length data ("first,second,third").
Code:
    int size = data.length();

size = 18
the number of characters in data.

Comparing Strings

Not the == and != of int or double values.
Compares the objects themselves and not their contents.
a == b, true when both handles point to the same object.

Code:
String a = "Some Text“;
String b = a;

Both a and b are handles to the same object.
Changes to the String pointed to by a, those changes will also be present in b because both are actually referencing the same object.
Making a copy of a:

Code:
String b = a + "";

In this case, b == a is false.

Sring Compare Functions
Code:
        public boolean equals (String)

        public int compareTo (String)


Equality
Code:
    boolean theSame = name.equals("Bob");

Characters represented by numeric codes,
-Strings "Bob" and "bob" won't be equal.
-Whenever comparing values that aren't supposed to be case sensitive, convert to upper case or lower case before compare.

Lexical Ordering
Whether one String comes before another String in the dictionary.

Code:
        a.compareTo(b):

negative number if this string comes before the parameter string (i.e. a comes before b in the dictionary)
0 if the two Strings are equal
positive number if this string comes after the parameter string in the dictionary (i.e. a comes after b in the dictionary)

Changing the Case of a String
Code:
        public String toUpperCase()

        public String toLowerCase()

    String first = "Bill";
    String allUpper = first.toUpperCase(); String allLower = first.toLowerCase();

allUpper = "BILL"
allLower = "bill".

String Practice:
A social insurance number is often stored in a computer as a 32 bit int value. Write the JAVA code to convert this int value into the standard SIN form of 999-999-999 (where the 9s are replaced by the digits of the SIN).

In many hospitals, a patient's name is output in the form of HUN, Attila T. Write the JAVA code to take a name in the form of Attila The Hun and convert it to this format.
Code:
String name  = “Attila The Hun”
int first = name.indexOf( “ “ );
int second = name.indexof(“ “ , first +1 );
String sickie = name.substring (second + 1).toUpperCase() + “, “ + name.substring(0,first)+ “ “ + name.substring(first + 1, first + 2 ) + “.“


JAVA-011: class Graphics

Sreen Coordinates
Vertical position from the top of the monitor downwards
Mathematics origin at the bottom left.
Monitors build image from top-to-bottom
CG uses upper left corner as origin.

drawline
Draws a line, in the current color, from the starting point (startX, startY) to the finish point (finishX, finishY).
These co-ordinates must be integer values.
Code:
drawLine (startX, startY, finishX, finishY)

drawRect
drawRect method draws a Rectangle, in the current color
Upper left corner (StartX, StartY).
Horizontal size is width.
Vertically size is height.
Only draws the outline. Interior unaffected.
All values (start X, start Y, width and height) must be integer values.
Code:
drawRect (startX, startY, width, height)

Examples
Create a rectangle (75, 50) that is 150 pixels wide and 100 lines high:
Code:
g.drawRect (75, 50, 150, 100);

Create a square 40 pixels on a side, at 150, 200:

Code:
g.drawRect (150 - 40 / 2, 200 - 40 / 2, 40, 40);
Or
Code:
g.drawRect (130, 180, 40, 40);


Draw Oval
The drawOval method draws an Oval, in the current color, inscribed in rectangle whose upper left corner is (StartX, StartY).
Horizontal size is width.
Vertically sizeis height.
The rectangle does not appear, only the oval
Draws outline in current color. The interior is unaffected.
Special Note: To draw a circle, make width = height.
All values (startX, startY, width and height) must be integer values.
Code:
drawOval (startX, startY, width, height)

Example
Draw an oval at 45, 65 and is 135 pixels wide and 65 lines high:
Code:
g.drawOval (45, 65, 135, 65);
Draw a circle with radius 25 centered at 150, 200:
Code:
g.drawOval (150-25, 200-25, 25*2, 25*2);
Or
Code:
g.drawOval (125, 175, 50, 50);

drawString
Draws the Text (String)
At location (StartX, StartY).
Not the upper left corner
Fonts defined relative to the base line
Starting point (Start X, Start Y) must be integers.
Code:
drawString (Text, startX, startY)

Font and drawString
Uses the current Font. Font is style of the Font (Helvetica or New York), size (16) and Weight (Bold).
Standard size is 12
Standard weight is Plain
If we want new font:
Code:
    newFont(“Courier New”, Font._____, 32)
____ Can have PLAIN, ITALIC, BOLD

fillRect
fillRect method fills a Rectangle with current color
Upper left is (StartX, StartY).
Size is width x height.

All values (startX, startY, width and height) must be integer values.
Code:
fillRect (startX, startY, width, height)

Examples
Create a rectangle at 75, 50 that is 150 x 100:
Code:
g.fillRect (75, 50, 150, 100);
Create a square 40 pixels on a side, at 150, 200:
Code:
g.fillRect (150 - 40 / 2, 200 - 40 / 2, 40, 40);
Or
Code:
g.fillRect (130, 180, 40, 40);

fillOval
fillOval fills an Oval with current color,
Inscirbed in rectangle with upper left corner (StartX, StartY) and size width x height.
The rectangle does not appear, only the oval.

Special Note: To draw a circle, make width = height.
All values (start X, start Y, width and height) must be integer values.
Code:
fillOval (startX, startY, width, height)

Examples
Fill an oval at 45, 65 and is 135 pixels wide and 65 lines high:
Code:
g.fillOval (45, 65, 135, 65);
Fill a circle with a radius of 25 centered at 150, 200:
Code:
g.fillOval (150 - 25, 200 - 25, 25 * 2, 25 * 2);
Or
Code:
g.fillOval (125, 175, 50, 50);


setBackground(Color)
Associated with the applet rather than the Graphics object. It changes the color of the background (normally white).
Must Color variable

Pre-defined color constants begin with "Color.". The following are the color constants defined: black, blue, cyan, darkGray, gray, green, magenta, orange, pink, red, white and yellow. If you want a red color, you'd use the value Color.red.
Example 1: To change the background of the Applet to blue:
Code:
setBackground (Color.Blue);

User-defined colors created using new.
Red, green and blue (0 to 255). So if we wanted to create a Color whose red,green,blue values were (75, 95, 175), we put new Color(75, 95, 175).
Example 2: Changing the background to the color having red=75, green=95 and blue=175:

Code:
setBackground (new Color (75, 95, 175));

setColor(Color)
Changes the color used to draw or fill the Graphics objects
Color is either a pre-defined constant or a user-defined Color.


drawImage
Previous methods are fine for simple drawings and charts
More complex would be difficult to create using lines, ovals and rectangles.
class Image to handle complete graphics images.
Code:
drawImage (Image, CornerX, CornerY, Observer)

Display an image at (CornerX, CornerY)
Observer handles the notification when a really huge image is finished displaying.
Small images use null

Example: Draw a Spacecraft
getImage method part of the Applet class
Same directory as the HTM file that runs our applet to use the following:
Instance Variable
Code:
    Image spacecraft;
In init:
Code:
Image spacecraft =     
        getImage(getDocumentBase(),
        "BE2.0005.gif");
In paint:
Code:
g.drawImage (spacecraft, 150, 75, null);


Fast Computers and Images
Image read by getImage won't finished until after display occurs.
Don’t see image until you force the screen to redraw
minimize the applet and then expand it again
Alternate method is to delay Applet until the image read is done.

MediaTracker Class
Code:
MediaTracker tracker = new MediaTracker(this);
spacecraft = getImage(getDocumentBase(), “spacecraft.gif”);
tracker.addImage (spacecraft, 0);
        // Tell the tracker about the Image
try {
    tracker.waitForAll();
    } catch (InterruptedException e) { }
        // Wait until the image read is done

Graphics at Java Site:
http://java.sun.com/j2se/1.5.0/docs/api/...phics.html

http://java.sun.com/j2se/1.5.0/docs/api/...Color.html


Java-012: Conditional Statements
Making Decisions
If, If-Else and Switch

Conditions
JAVA uses an if-then-else statement which is very similar to the if-then-else in Pseudo-Code
If answer < 10 Then
Say “That’s a Good Answer”

Code:
if (answer < 10)
      System.out.println(“That’s a Good Answer”);

If answer < 10 Then
That’s a Good Answer
Else
That’s not a Good Answer

Code:
if (answer < 10)
    System.out.println(“ That’s a Good Answer”);
else
    System.out.println(“ That’s not a Good Answer”);


Comparing Values in C++ and Boolean Logic in C++
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
== is equal to
!= is not equal to
AND is &&
OR is ||
NOT is !

Examples
Convert the following lines of Pseudo-Code in JAVA:
If x > y or > z Then
Code:
if (x > y || x > z)
If a < answer and answer < b Then
Code:
if (a < answer && answer < b)
If a is not equal to b or not equal to c Then
Code:
if (a != b || a != c)


Switch
Sometimes you have a range of values to put into a conditional
Switch allows you to select based on cases

Examples
Suppose 90+ is A, 80 to 90 is B, 70 to 80 is C, 60 to 70 is D and everything else is F
Code:
if (mark >= 90)
      letter = 'A';
else if (mark >= 80)
      letter = 'B';
else if (mark >= 70)
      letter = 'C';
else if (mark >= 60)
      letter = 'D';
else
      letter = 'F';
Code:
int mark;
String grade;

switch (mark / 10) {
case 10:
case 9: grade = “A”; break;
case 8: grade = “B”; break;
case 7: grade = “C”; break;
case 6: grade = “D”; break;
default: grade = “F”; break;
}

Value in parentheses after switch
Must be ordinal value:
char, byte, short, int, long

Why (int)(mark / 10) in the switch?
Need to change percentage grades into ranges. Otherwise we’d have to have one case statement for every grade
0 = F
1 = F
2 = F
3 = F
4 = F
5 = F
6 = D
7 = C
8 = B
9 = A
(int) type coerce to drop the fractional part

Why the empty case 10?
Case 10 deals with the 100. It’s an A, too
break; is the statement that tells JAVA that the processing is finished for that case.
Case 10 (with no breakWink simply falls through to case 9 and makes the grade an ‘A’

Why default?
The alternative would be a case statement for everything from 0 through 5.
Too much typing.
Danger is that 110 is an F

Input in JAVA

Up to now, no user input
Easier to test programs with input rather than fixed values
In JAVA 1.5 and later, Scanner class

Import statement at start of program

Code:
        import java.util.Scanner;

Handle variable to Scanner object

Code:
            Scanner input;

Can be local to a method if only one method does input
Can be instance variable.

Creating the Scanner object using System.in as its source:

Code:
        input = new Scanner (System.in);

Only need to create a single time
NOT for each input

Reading a Integer
Signature:

Code:
            int nextInt()

public class IntegerReader {
      static public void main() {
            Scanner input = new Scanner(System.in);
        System.out.print ("Enter an Integer:");

        int answer = input.nextInt();

        System.out.println("You entered "+answer);
        }
      }

Scanner only does input.
-Tell the user what is expected as an input
--No prompt & program will just sit there.
--Confusing for the user
--Output a prompt before doing input.
---A prompt is an output that tells what the program is waiting for.
---Uses System.out.print instead of System.out.println

JAVA-013: Pre-Test Loop
Iteration & the While Loop


While Loop
Once again, the while loop (our pre-test loop) looks very similar in JAVA and pseudo-code:
While Condition
Loop Statements
Code:
while (condition) {
       Loop Statements
       }

Better to make sure input is correct rather than catching errors later

Prime the loop values to be illegal
While the loop values are illegal
Prompt for & read the values
Process & output

Relative Problems
Illegal values:
Negative Mass
Speed >= speed of light
Speed < 0

Code:
public class Relativity
public static void main() {
Scanner input = new Scanner(System.in);
double mass, speed = -1.0;
while (mass < 0 || speed < 0 || speed >= 300000) {
    System.out.print(“Enter Mass:”);
    mass = input.nextDouble();
    System.out.print(“Enter Speed:”);
    speed = input.nextDouble();
    }
double massR = mass / Math.sqrt(1.0 - speed * speed / 9E10);
System.out.println(“Relativistic Mass = “ + massR);
}

Sentinel Value loop
Initialize the Variables you'll need for your processing
Read a Value
While Value isn't the Sentinel Value
Process the Value
Read A Value
Output The Results of Your Processing

Summation of Example
It's easier to see how this works if we use a real problem.
Suppose we want to add up a list of values (both positive and negative). Our program will stop and output the total when the user enters a zero(0).
Sentinel value is zero

Total = 0
Read a Value
While Value isn't zero
Add Value to Total
Read A Value
Output Total

JAVA
Code:
public class SentinelLoop {
    Scanner data;

    public static void main () {
        data = new Scanner(System.in);
        int total;
        System.out.print (“Value=?”);
        int value = data.nextInt();
        while (value != 0) {
            total += value;

            System.out.print (“Value=?”);
            value = data.nextInt();
            }
        System.out.println(“Total = “ + total);
        }
Practice
Average Application and Largest Value Application
pulic class avg
{
public static void main ()
{
scanner input = new Scanner(System.in);
int total = 0, counter = 0;
int value = input.nextInt();
while ( value != 0 )
{
total += value
counter++;
Value = input.nextInt();
}
System.out.println(“average=“ + value)

JAVA-014: Post-Test Loop
Do-while
Once again, the do-while loop (our post-test loop) looks very similar in JAVA and pseudo-code:
Code:
Do
    Loop Statements
While Condition
Code:
do {
       Loop Statements
     } while (condition);
Code:
Do
    Get a Value
While value is illegal


Summation Example
Create a single question multiple choice exam concerning the capital of the province of Alberta. In this test, the correct answer will be 'C' (isn't it always?)

Multiple Choice
Output the Question
Code:
Do
    Get the Person's Guess
While the Guess isn't A, B, C or D
If the Guess is a C
    Output that they got it right
Else
    Tell them that the answer was C

Code:
public static void main() {
    String guess;
    input = new Scanner (System.in);
    System.out.println(“Is the capital of Alberta:”); System.out.println(
        “    A. Calgary, B. Ottawa, C. Edmonton, D. Vegreville”);
    do {
          System.out.print(“Select A, B, C or D:”);
          guess = input.next();
          guess = guess.toUpperCase().substring(0, 1);
          } while (!guess.equals(“A”) && !guess.equals(“B”) &&
            !guess.equals(“C”) && !guess.equals(“D”));
    if (guess.equals(“C”))
        System.out.println(“That is correct!”); else
        System.out.println(“The correct answer is C”);
    }
Practice Questions
A metal ball's mass can be calculated from it's radius and density using the formula: mass = 4/3 * PI * density * radius^3. Write a program to calculate the mass of a metal ball from user entered values for density and radius. Make sure both the radius and density are positive values.

Write a program using a do-while loop that prints out the Fibonacci numbers until the Fibonacci number is greater than 100. Fibonacci numbers are calculated by keeping track of the last two Fibonacci numbers (originally these will both be 1). The next value is the sum of the two preceding values. Fib(0) = 1, Fib(1) = 1, Fib(2) = Fib(0) + Fib(1) = 1 + 1 = 2, Fib(3) = Fib(2) + Fib(1) = 2 + 1 = 3, and so on. Use a do-while loop in your solution.


JAVA-015: The Definite Loop

The for Loop
Once again, the for loop (our definite loop) looks very similar in JAVA and pseudo-code:
Code:
For Index=start to end modification
Loop Statements
Code:
for (int variable=start;variable <= end;modification)
       Loop Statement

Code:
For i=1 to 10 adding one each time
    Output I

for (int i=1;i <= 10;i++)
    System.out.println(“I = “ + i);
Initialization
The initialization statement is any statement in JAVA that sets up your loop values.
Usually takes the form of
Code:
            int index=value;

This statement declares a new int variable
(called index in this case but it could be anything)
Only exists inside the for loop. Can’t be used outside the loop.
Set to value that follows the equal sign.
Can be a simple number or a calculation.
If you want to use the loop index outside the loop, declare the variable first and then use it like this:

Code:
            int d = 0;
            for (;d <= 10; d++)

Continuation Condition
A boolean condition that determines whether or not to do the loop body again.
Same form as condition on if-else, while, do-while
As simple or as complex as necessary
True means do the loop body again

Change
Optional statement
Changes the values of the index variable.
Any calculation is valid
x += 40 - adds 40 to x each time
p-- - subtracts one from p each time
binary *= 2 - multiplies binary by 2 each time

Infinite Loops
Any loop (while, do-while or for) can have a condition written so that it will never stop
This is an infinite loop

Example:
for ( int i = 0; i <0 ; i++ )
{
g.drawOval( 50 +40+I, 50, 40, 40)
}
-------------------------------------------------------------------------------
for ( int r = 0; r < 10; r++ )
{
for ( int c = 0; c <= r; r++ )
{
System.out.print(“ * ”)
}
System.out.println();
}
-------------------------------------------------------------------------------
for ( int r = 0; r < 8; r ++ )
{
for ( int c = 0; c < 8; c++ )
{
if( ( r + c ) % = 1 )
System.print.out(“[ * ]”);
else
System.print.out(“[ ]”);
}
System.out.println();
}


Functions: Writing Your Own Methods

User Defined
Been using methods now for a while.
With Applets: Paint & init
Mathematical functions: Math.cos(theta)
Only modifying special methods
Using pre-defined ones.
Next stage: learn how to create your own methods.

Procedural Methods vs Functions
Two kinds of methods in JAVA.
Procedural methods perform an activity using the instance variables.
Don't return a value though.
Init & Paint method in an Applet

Code:
        public void init()
        public void paint (Graphics g)


public void paint (Graphics g)
In both cases, the procedural method is doing some task.
Use/change the values in instance variables (init)
Displays to the screen using Graphics (paint)
Returns no value for further processing.
Return type is void.

Functions
Functions calculate values and return them for further processing.
Math library

Code:
public double cos(double theta)
double instead of void. Returns value for future processing:
Code:
double x = 150.0 * Math.cos(0.175);

Parameters: Actual and Formal
Parameters are values passed to the method in brackets after the name of the method.
Used as part of task method to perform.

Code:
public double cosine (double theta)

Formal parameter is name for parameter used in method
Actual parameter is variable or value we put in the brackets when we use the method.

Code:
double angle = Math.toRadians(35.0);
double xLocation = 150.0 * Math.cos(angle);

Actual parameter to toRadians method is 35.0.
Signature of toRadians method

Code:
public static double toRadians(double angdeg)

Formal parameter called angdeg.

When method used
Value in actual parameter is passed into the method via the formal parameter.
Pass by value because we only pass the value not the actual parameter itself.
If we change the parameter in the method, the outside value DOES NOT change

Writing your own Methods
Methods are always part of a class that you are creating.
Between the opening brace after the class heading line and the final closing brace.
Each method has own header line that sets its signature.
The signature is the definition as to what the method produces as output, it's name and the kind of information it requires as its parameters.

A Factorial
4! = 4 * 3 * 2 * 1 = 24
6! = 6 * 5 * 4 * 3 * 2 * 1 = 720

Since we are creating a function (let's call it factorial), we first have to decide on what it is going to return.
Multiplying integers together, maybe use int.
Factorial grows too fast
10! is already 3,628,800
Use long instead

Method signature:

Code:
public long factorial ( ) {

Decide on parameter if any.
Not required (init or Math.random).
We have number we want to take our factorial of.
Standard int should work here.

Code:
public long factorial (int n) {

So, how do we calculate the factorial?

Code:
        Result = 1
        For I=2 to N adding one each time
            Result = Result * I
        Return Result

Code:
public long factorial (int n) {
    long result = 1;

    for (int i=2;i <= n;i++)
        result *= i;
    return result;
    }

return keyword tells the function the value to use as the answer for the function.
When return is set, the function immediately exits.
NOTHING after the return statement is done once the return statement is performed

Using a fcuntion (output)
Code:
public void paint (Graphics g) {
    g.drawString ("10! = " + factorial(10),
            50, 50);
    }
Method to return a long value.
Formal parameters (n & m) both int.
Code:
public long choose (int m, int n) {
    return factorial(n) /
            (factorial(m) * factorial(n-m));
    }

When choose is called:
calls factorial function three times:
factorial (n)
factorial (m)
factorial (n-m)

Rocket Range
The range a rocket lands down range from its launch site can be calculated if you know the rocket's launch speed and launch angle. The formula for the range is:

range = speed^2 * cos(angle) * sin(angle) / 5

Write a function that accepts the angle and speed and returns the range. Have the function accept its angle in degrees but remember that the Math library requires that your angle be in radians.

Code:
public double range(double v, double a) {
    double angle = Math.toRadians(a);
    return v * v * cos(angle) * sin(angle) /
                     5.0;
    }

JAVA-016: Procedures
Functions help by performing calculation and returning answer
Procedures help by allowing us to set up a method to perform some task that may need performed in several places in a program.

Astronomy
Create a night sky picture with several randomly placed stars.
Stars as traditional five pointed stars like the one to the left.
Stars of different sizes.

theta = 90 + 144 * i
horizontal = centerX + radius * cos (theta)
vertical = centerY + radius * sin (theta)

i goes 0 through 4

Psuedo Code
Code:
oldX = centerX
oldY = centerY - radius
for pt=1 to 5 step by one each time
    angle = radians of angle in degrees (pt * 144 + 90)
    newX = centerX + radius * cos(radians)
    newY = centerY - radius * sin(radians)
    draw Line from oldX,oldY to newX, newY
    oldX = newX
    oldY = newY
Parameters
Three pieces of information:
centerX, centerY and radius. (parameters)
Graphics object (for display)

Code:
public void star (Graphics g, double radius,
            double centerX, double centerY) {
    int oldX, oldY, newX, newY;
    double radians;
    
    oldX = (int)(0.5 + centerX);
    oldY = (int)(0.5 + centerY - radius);
    for (int pt=1;pt < 6;pt++) {
        radians = Math.toRadians(pt * 144 + 90);
        newX = (int)(0.5 + centerX + radius *    Math.cos(radians));
        newY = (int)(0.5 + centerY + radius * Math.sin(radians));
        g.drawLine(oldX, oldY, newX, newY);
        oldX = newX;
        oldY = newY;
        }
    }
Night Sky Applet
Code:
public void paint (Graphics g) {
    g.setColor(Color.black);
    g.fillRect(0, 0, 500, 500);

    g.setColor(Color.white);
    for (int i = 0;i < 100;i++)
        star(g, Math.random() * 10,     
            Math.random() * 500,
            Math.random() * 500);
    }
Procedural Method Practice
In many games, you see the action from slightly above and at an angle. This is often simulated in the older games with a 2D trick instead of actually using the 3D graphic display system. The basis for this kind of display is a rotated rectangle that ends up looking like a diamond.

Write a method to draw a diamond. Each diamond is specified by a center location, a height and width. Be sure to include your Graphics object as you want to display the diamond from the method.

Code:
Draw Line Center X - width, Center Y to Center X, Center Y - height
Draw Line Center X, Center Y - height to Center X + width, Center Y - height
Draw a Line from Center X + width, Center Y to Center X, Center Y + height - height
Draw a Line from Center X, Center Y + height to Center X - width, Center Y - height

Code:
public void diamond(Graphics g, int centerX,
        int centerY, int width, int height) {
    g.drawLine(centerX - width, centerY,
            centerX, centerY - height);
    g.drawLine(centerX, centerY - height,
            centerX + width, centerY);
    g.drawLine(centerX + width, centerY,     
            centerX, centerY + height);
    g.drawLine(centerX, centerY + height,     
            centerX - width, centerY);
    }


JAVA paint Method for Applet
public static final int WIDTH = 40;
public static final int HEIGHT = 20;

public void paint(Graphics g) {
for (int y = 0;y < 4;y++)
for (int x = 0;x < 4;x++)
diamond (g, 200 + WIDTH * (x - y),
200 + HEIGHT * (x + y),
WIDTH, HEIGHT);

}

JAVA-018: Recursion
Methods That Call Themselves

Our methods call other methods.
range function used Math.cos as part of its calculation.
This is very common
There are algorithms that have the method call itself to create the solution!
Called recursive algorithms.

Recursive Factorial
Code:
Public long factorial (int n) {
    if (n <= 1)
        return 1;
    else
        return n * factorial (n);
    }
Towers of Hanoi
Legend has it that there is a temple of monks in Vietnam who spend their entire lives moving gold disks from one crystal rod to another crystal rod. They have very strict rules about the moves though. Only one disk may be moved at a time and no larger disk can be placed on a smaller one.
The monks have three rods but 64 disks. It is believed that once all of the disks have been moved from one rod to another, this would signal the end of the universe. Now 64 is a huge number of disks and it would take 18,446,744,073,709,551,615 moves to complete the task.
Let’s try it with something smaller

No simple linear solution for this one.
Recursion is our only effective choice.
Suppose we start with four disks.
Need to move the top three disks off to the temporary rod
Move the bottom disk to its final rod.
Move the three we have on the temporary rod onto the target rod.

Can’t just pick up and move three disks as a block, that's not allowed.
Our method moves disks from one rod to another
Use it to move the top three from rod to rod.
No point in moving a tower if there's no tower to move (single disk).


TowersOfHanoi (Disk Count, Source, Target, Temporary)
Code:
If Disk Count > 1
    TowersOfHanoi (Disk Count - 1, Source,
                Temporary, Target)
Move Disk from Source to Target
If Disk Count > 1
    TowersOfHanoi (Disk Count - 1,         
                Temporary, Target, Source)

JAVA-019: The Array
A Composite Structure
To hold a Collection of Values

Background
To this point Every variable held single value
Primitive (an int or double)
A Handle to an object (a String or a Graphics).
Useful but limited
Most problems need more
For example, suppose you want to enter a list of telephone numbers and sort them into ascending order. To solve this problem, we need something that allows us to put a whole list of values into a variable and then reference each value individually, moving each about until they are in order.

A collection of values is called an array.
Consists of a number of slots
Defined when we create the array
Each slot holds one value
Each slot would could a different number

Index number isn't contents.
Array at location 0 (array[0]) is NOT zero.
Index of the first element is ALWAYS zero (not one).
Array index numbers go from zero up to one less than the number of elements in the array.
Maximum index ten element array is NINE not TEN.

Three step process:

1. Create the Handle for the entire array as a variable.
2. Allocate space for the slots in the array in a method.
3. Fill each slot in the array with a value or an allocated Object.

Example
Suppose we want to create an collection of images of eight dolphin ImageIcons using files 'dolphin.0000.gif', 'dolphin.0001.gif', 'dolphin.0002.gif' up to 'dolphin.0007.gif':

Likely used everywhere in Applet, add the following line after the class header:
Code:
    private ImageIcon dolphin[];
ImageIcon tells kind of information in each slot
Each slot in array 'dolphin' is a ImageIcons
Only handle to array. The array doesn't exist yet.

Creating Slots
Need to allocate space for the array:

Code:
        dolphin = new ImageIcon[8];

If in init, DON'T put ImageIcon ahead of dolphin.
Creates a local variable that would mask the instance variable we'd created before.
new keyword creates objects.
An array of Objects in this case.
Size (the number of slots) in square brackets
This creates eight element array with each element (slot) an ImageIcon.
Slots numbered 0 through 7

Filling The Slots
8 ImageIcon slots now but nothing in each slot.
null is used to indicate an empty Object
Delete an Object: set handle to null
For primitives different empty values are used.
Numerical types use zero
boolean uses false.
Put a value into each
Read them from files. File names formed a numbered set of files: Dolphin.0001.gif, Dolphin.0002.gif, etc.
Code:
    for (int i=0;i < 8;i++)
        dolphin[i] = new ImageIcon(
            "Dolphin.000"+(i+1)+".gif"));

Accessing a Slot
Name the variable
Add index in square brackets.
The index has integer and positive.
Less than the length of the array.
Number or integer variable.
If variable, then number in variable used as index value.

Each slot holds one element of whatever type the array was defined with.
You can assign values to each slot independently or use the slot value in a calculation exactly as if it were a normal variable.
JAVA does not prevent you from putting in an illegal value for an index (< 0 or >= length).
IndexOutOfBoundsException.

Example
Suppose we want to enter 10 floating numbers and find the maximum number. An array is one of the best ways to solve this problem. Let's create an application this time. To solve the problem, we would want to do the following:
Code:
    Create a 10 element array of numbers
    For each slot
        Read a value into the slot
    Set Maximum to the First Slot value
        For each remaining slot
            If current slot value > Maximum
                Maximum = current slot value
    Output Maximum

Code:
import java.util.Scanner;
public class ArrayMaximum {
    public static void main() {
        Scanner input = new Scanner (System.in);
        double maximum;
        double value[] = new double[10];


        for (int i = 0;i < 10;i++) {

            System.out.print("Enter value #" + (i+1) + ":");
            value[i] = input.nextDouble();

            }

        maximum = value[0];

        for (int i = 1;i < 10;i++)

            if (value[i] > maximum)
                maximum = value[i];
        System.out.println ("The largest value is " + maximum);

        }
    }

Thanks for such hard effort
wow! i cannot understand a thing! but this are great! heheh! you are a hard working man! i have no future in Java programming! hehehe! anyways thanks mr. moderator for the knowledge you share! hehe..
Its ok. Once you can understand the basics of programming, this stuff will make sense.
eally! i really want to learn.. i also want to make a website.. but i dont know where to start... huhuuh..
It is fun to learn how to program simple and cool things.
Zhong how many points did you get from this? If quoting is still legal maybe many people will do that hahaha!! btw this looks hard! haha
I coulda gotten 3000 points from it, but i didnt care.
wow hahaha! Limme guard your post from quoting that is soo expensive. xD
hehehehehe... i wish quoting is not illegal... but.. i think i will be also unfair... hehehehe...
Pages: 1 2 3
Reference URL's