cHILL ‘em All

Recent bits and bobs – Switch, Save/Load, For:each, Iterator

Posted by: chilloxk on: January 31, 2009

The lab for monday is almost entirely the same as the DVD labs. Here I’ll post some minor bits we went over in lectures which might help a bit.

Switch Statements

These are handy for checking specific things like numbers’ equality. They are useful if you want to have menus and use numbers for imput and the like.

eg:

we have a menu that says ‘please enter a number to select an option’, which is stored in an int called choice:

println(“please enter a number to select an option: “);

int choice = readInt();

the syntac for switch is:

switch (expression){

case n:

method();

break;

case n+1:

method2();

break;

}

this checks if expression is equal to n, if not, n+1, and will keep going down the list. it will execute the methods inside the case: until it comes to break; which ends the statement.

SAVE / LOAD

as in the lectures:

save:

saveToFile(dvds, “DVDs.xml”);

in this case, what happens is the contents of dvds(which is an arrayList of type String) is saved in the file called DVDs.xml in the directory your project is saved in.

load:

dvds = (ArrayList<String>) readFromFile(“DVDs.xml”);

this overwrited the file dvds (which is an ArrayList<String>) with the contents of the file DVDs.xml in the project directory.

FOR:EACH LOOP

Watch out with these, in a for:each loop, you cycle through elements of an array, arraylist or whatever, but you cannot modify the contents of the thing you are cycling though. It actually gives you a copy of what is contained, not the file itself.

syntax:     for(type anyname: listname)

type: String, int, DVD, Song.

anyname: the name which you will refer to each element by.

listname: the exact name of the array/ArrayList.

eg:

public void listDVDs(){

for(String moo: dvds)

{    println(dvd);    }

}

This will pick the first element in the arrayList ‘dvds’ (which holds String names), which shall be refered to as moo, and then execute whatever is inside the curly brackets. in this case it prints them out.

If it held DVD types, this would print the names of the dvds:

public void listDVDs(){

for(DVD moo: dvds)

{   print( moo.getTitle() );    }

}

Because we would get each DVD object stored in the arrayList, and all its methods inside it too, like a normal for loop.

ITERATOR

Don’t entirely know much about these, just that they are ways of cycling through and altering elements in lists/sets. Similar to a for-loop but with it’s own methods.

import the use of it by using: import java.util.Iterator;

we create it by the following: (not sure on the capital or small ‘i’/'I’)

Iterator<Type> iteratorname = collection.iterator();

eg: Iterator<DVD> it = dvds.iterator();

this creates an iterator which can cycle through DVD objects, we will call it ‘it’, and it will be attached to the dvds arrayList collection.

this iterator has its own methods;

hasNext() – which returns a true/false if there is another element in the list.

and next() – which gets the next element.

used generally (for the moment) like this:

while(it.hasNext() )

{ it.next(); }

to print the name of the DVDs:

while(it.hasNext() )

{ println(it.next().getTitle() ); }

Next: HashSets and HastMaps

specific questions to chilloxk[-at-]hotmail(-dot-).COM



Java 3: More on arrays and basic ArrayList

Posted by: chilloxk on: January 26, 2009

Smash.

// (Some things needed for the assignment)

if, for any reason,(hint) you need to access an array outside of a
class, you will need to create a method to access that method
(basically, you will need 2: one method (a getter) that returns the
full array, and another (another getter) that returns just the value
of the array that you want.

This is slightly complicated, I didn’t cop it till Mairead answered an
email I sent to her.

The reason you need to do this is simple:
-you create the array as PRIVATE, therefore it cannot be accessed
outside the CLASS it is created in.
-this means that all the elements are also PRIVATE.

So to access them, you need something like:

// will return the entire array
public String/int/double accessArray()
{
return String/int/double array[];
}

// will return the contents of ‘i’
public String/int/double accessArrayElement(int i)
{
return String/int/double array[i];
}

ArrayLists are some job.

You can do the exact same stuff as arrays, storing data wise, but you
don’t have to specify the size of the array initially.
Better because:
- save memory in the PC
- can’t fill it

creation:

ArrayList<String/TicketMachine/int/double> smash = new

ArrayList<String/TicketMachine/int/double>;

this String/TicketMachine/int/double arraylist is created and referred
to as smash.

again, it can only hold the above element^.

It differs to an array in some ways, namely;

arrays are added to by doing this:
array[i] = x;
that means x is added to index i of the array.

(will refer to the arraylist as smash)
arraylists are added to by doing this:
smash.add(x);
this will add x to the arraylist smash’s NEXT FREE POSITION

to remove an element:
smash.remove(i);
this will remove the i’th element in the arraylist smash

the Length of the ArrayList is referred to as a method: length()

So if it’s 10 elements long, it’s labelled from 0 – 9.

to access data in the arraylist;

smash.get(i);

( the array equivalent is:
array[i]; )

for instance, if I created an ArrayList that held a bank account

ArrayList<BankAccount> bacc = new ArrayList<BankAccount>;

add account:
bacc.add(cust_1);

or remove account in position 0.
bacc.remove(0);

or get the name of the person in that arrayList in position 0.

bacc.get(0).getName();

//————————-
create a method that returns all the people’s names in the arrayList:

public String getTheNames()
{
String temp = ” “; (make it an empty string)

for(int i = 0; i < bacc.length(); i++)
{
temp  = “” + temp + bacc.get(i).getName() + “, “;
}
return temp;
}

I think you have to have the “” which ‘tells’ the compiler that it’s a
string it’s adding to.
If you’re not sure, google: string concatenation. prob better off doing that.

temp  = “” + temp + bacc.get(i).getName() + “, “;
(line by line: )

‘ temp = ‘ -> if you dont know that this means at this stage… FUCK OFF. hah.

‘ “” ‘ -> this is just an empy String

‘ + temp ‘ -> adds temp to whats already in temp and what’s in “”

‘ + bacc.get(i).getName() ‘ -> adds the getName() value, which is in
get(i), which is in bacc.

‘ + “, ” ‘ -> adds a comma and then a space after the above are added.

Java 2: Basic Arrays

Posted by: chilloxk on: January 26, 2009

Right now, on a basic level, arrays are fucking fantastic.
They are a way of storing data. The data they can store is predefined
by the creator. The size of the array is also predefined. Neither can they
be changed. The fact that the max size cannot be changed is where
arrays fall down, so that’s why we use ArrayLists. But you need to
understand arrays first.
How you create arrays:
String[] a = new String[5];
This creates an array, which can hold only Strings, it is of size 5.

int[] shit;
shit = new int[10];
The first creates the address block in memory, the second assigns the
size of 10. Mairead is mad for that shit.

Visualise it like so:
{ [] [] [] [] [] }
It starts at 0, so you could consider the element names are
{ a[0], a[1], a[2], a[3], a[4] }

Using for loops is really just about cycling through array’s elements.
It would be possible, if you wanted to assign all the values of the
int array equal to 0, to do this:
a[0] = 0;
a[1] = 0;
a[2] = 0;
a[3] = 0;
a[4] = 0;
But, as padraic kirwin says in maths, when u get to something of size
1000 it doesn’t make sense, that’s where for loops come in.
int[] smash = new int[1000]
// creates an array from  { smash[0], smash[1],… smash[999] }
for (int i = 0; i <= 999; i++)
{
a[i] = 0;
}
this makes all the elements in the array equal to 0.
why does this work? we’ll take it section by section.
the for loop is really a better structured while loop. when i write it
i think of it in 3 stages:
stage 1 = “int i = 0″, the initialisation stage
stage 2 = “i <= 999″, the while stage
stage 3 = “i++”, the finalisation stage
here, i provides a counter, but it’s also a way of accessing the array.

each pass of the loop, a[i] is accessed and made equal to 0.
because at the end of each loop, i++ is ‘done’, which means i is made
what it is currently plus 1. so after the nth pass of the loop, i ==
n.

so you could do different operations to it, such as:
a[i]  = a[i] + 1;
so this would make the value of a[i] equal to its current value, plus one.

a[i] = a[1] * [a2];
this would make the value of a[i], which of course will change each
time, be multiplied by the value of what is in element a[1] and a[2]

you might think ya whatever this is boring, which you are dead right.
The major thing about arrays is that you can store much more than
ints, chars or Strings, you can hold an entire class in each element
of the array,
which is great for storing things like records of information, etc.
when you store a class object in an array, all the methods and fields
can be accessed.
for instance: if we had a method called getName(), in a class Customer.
and we had an array that held customers:
Customer[] list = new Customer[5];
and this array was populated fully, as in it was full of customers:
Customer[0] = cust1;
..etc (cust1 would have to be already created)

we could find the name of the Customer in the Customer[] array, by doing:
Customer[0].getName();

this would mean, we could make a String value equal to this case, for
whatever reason:
String coolest = Customer[0].getName();

if this was in a for loop:
String coolest = Customer[i].getName();

when would you ever use that?

well imagine you wanted to get the name of the person in the array
with the highest balance:
(we need to assume that we have a getter method called getBalance)

public String getHighestBal()
{
int highestBal = 0;
String name = ” “;
// the reason you need to do that^, is because.. well I don’t know. i
think it just needs a value, if it is to be updated.
for (int i = 0; i < 5; i++)
{
if ( a[i].getBalance > highestBal )
{
highestBal = a[i].getBalance;
name = a[i].getName;
}
}
return name;
}
what happens:
- goes into a[i], which is initially a[0], and checks the Customer
object in there, checks if the balance is greater than the value we
created ‘highestBal’
if it is, makes the highestBal value equal to it.
then gets the name of the customer in this element of the array and
makes the ‘name’ String we created
goes back into the for loop until i is no longer less than 5, then the
return statement is carried out and it exits

Java 1: basics

Posted by: chilloxk on: January 26, 2009

For the Customer class:

First thing to do, you need to create the class.
For the Ticket Machine last week, creation of the class was done and
is always done by:

public class TicketMachine{

}

Everything goes inside the CLASS braces ( the { and } ). All other
methods, declorations, everything. They are the first and last braces
in the java file.

Mairead calls the Class the blueprint, but she never mentioned it is
the blueprint for each specific physical thing. Like a Customer, a
TicketMachine, a Car.
All classes start with a capital letter.

Right, the fields.
Fields store values.
If the field type is an int, a ‘char’, a “String”; that means they
hold integers, single characters, or a String of characters( ie a
sentince).

- Creating a field
If i wanted to create a field for the Customer class that held, for
example, someone’s favourite colour,
you would create a String type and name it something that made it
kinda obvious like favColour.
Note: you don’t have to, but it’s good to name them all in small
letters, until the start if a new word, then that in a cap, so if i
wanted to make a String called: When in Dome, I would write:

private String whenInDome;

What this actually does it it creates a space in the computers memory
called whenInDome, and says; “Right, this can only hold “String” ’s.

Imagine every field you create as a cardboard box, if you create, for example:

private int waa;

Then a cardboard box is set aside, its contents can only be ints, and
it’s got “waa” written on it because that is what it is now referred
to as.

So we’ve got our cardboard boxes set aside but there’s nothing in them
right now.

//======================

Going back to Customer.class

for the assignment, we need to create 3 of these ‘cardboard boxes’,
one that holds someone’s name, one that holds someone’s address
address,
and one that holds someone’s overdraft limit.

She even tells us what type we want, ie – as in the pdf,
String name, String address, and double overdraftLimit.

(double is similar to int, it just holds decimal points, you need that
for bank acc’s)

look up at the whenInDome and waa examples and make name, address and
overdraftLimit your self! fuckers..

//====================

Constructors

Right, when you create a class for the first time, everything that’s
(any assignments or anything, ill go into more detail)
in the constructor is what happens initially, if you didnt have a
constructor, nothing would happen when you created the class.

In the TicketMachine example, the constructor was something like:

public TicketMachine( )
{
total = 0;
balance = 0;
numCoins = 0;
}

what this did was take the value 0, and put it into our carboard box
called total that only stores ints.
it then puts the value 0, and puts in into the cardboard box called
balance that only stores ints, and ditto for numCoins.
THIS IS NOT THE NAME AS HAVING THE BOX EMPTY.

there is another thing about the contstructor. Lets say you didnt want
to set the initial balance to 0, you wanted that everytime you created
the class,
that you wanted to define what total, balance, and numCoins were. it
would look like this:

public TicketMachine(int newTotal, int newBalance, int newNumCoins)
{
total = newTotal;
balance = newBalance;
numCoins = newNumCoins;
}

in this example, the first line: public TicketMachine(int newTotal,
int newBalance, int newNumCoins)

this tells the compiler, (the thing that checks all your code to see
how wrong it is) that for TicketMachine, there are 3 parameters,
the first is an int, the second is an int, and the third is an int.

the actual names of the parameters mean nothing, but I always name
them newX, where X is the current thing they will be replacing. (eg
total and newTotal).

—Bringing this back to Customer, she wants you to set the name,
address, and overdraft limit.
I’m refusing to give out the actual code coz you wont learn shit,
but it’s not too bad when you think about it;

Substitute the names of the classes: Customer is the name we want,
TicketMachine was last week.
We have 3 variables (anything which value can be changed, ie vary)
that are in Customer, and these defined in the parameters( the ( )’s )
again,
and as she told us in the PDF she wants them to be.

They want to be the 3 things from our cardboard boxes that we created
earlier, the String type which is called name, the String type which
is called address,
and double (which holds a number with 2 decimal points) type called
overdraftLimit.

So going by this logic,

(as in the TicketMachine) int newTotal took in an int that we wanted
to call the ‘new total’ because it was to replace total by new total.
So here, we want to do the same, for all 3.

So here, we create Customer, like we created TicketMachine above, we
take in 3 parameters, like we did above,
and we must assign the values we took in, to the ‘cardboard boxes’ we
created earlier. something like “total = newTotal”.

//============================

========

Right, now for getters and setters.

Getters

When Mairead is on about getters and setters,
she means that getters are ‘methods’ (method = a block of code to
serve a specific purpose) that return a value of a specific
field/instance variable (field/instance variable = the cardboard boxes
created at the start).

when i create a method for returning a balance, as in TicketMachine:

public int getBalance( )
{
return balance;
}

the int means the value of the thing you are going to return is an int.
We know it’s an int because when we created our cardboard box we wrote
‘can only contain ints’ by saying
private int balance; (as way above)

what this means is when you write ‘getBalance( )’ anywhere, your
actually using the value of balance,
so whenever you say, in any way ‘getBalance( )’, its treated a number,
because its actually a name of a number.

Kinda weird concept, but when something is returned, think of it as
the name of the method (getBalance( ) ) actually holds the value of
whatever you returned.

so,

public type getName( )
{
return name;
}

type = int, String, char, double, etc…
Name/name = the cardboard box name that holds a value (fields) that
was created at the start.

just use that formula for all the getters you need. (in this case for
name, address, overdraftLimit)

Setters

A bit more tricky, generally you will have to put in some condition
checks here, ( if / else statements, while loops, etc)
Setters take in a value, or more than one value (seperate by commas),
and set something to that value ( ie make it equal to the newValue)

TicketMachine example (something like this):

public void setBalance(int newBalance)
{
if ( newBalance < 0 )
{
balance = newBalance;
}
else{
System.out.println(“Error: Enter a positive number”);
}
}

the void in the name means there is no return value.
I’ll leave a note on public/private below.

Obviously, we can’t have a balance below 0, it wouldn’t make any sense.

All setters take this kind of format,

if (conditions associated with it) (each condition seperated by &&
and, || or, == equal to, and !=, not equal to)

so you could have:

public void setBalance(int newBalance)
{
if ( ( newBalance > 0 ) && (newBalance  < 300))

so if the value newBalance is 50, [setBalance(50); means newBalance is
50, as your entering 50 into the parameters, thats how it works] then
what ever is in the ‘if’ parts brackets gets executed, here balance =
newBalance.
Generally she gives us conditions but sometimes we’ll have to cop them
ourselves.

like overdraftLimit needs to be less than or equal to 0.

the else part is executed when the condition check if false, for
instance if 400 was entered into setBalance. setBalance(400);

here, “Error: Enter a positive number”, is shown up on screen.
“System.out.println” is used to show stuff on the monitor.

all setters are done this way.

public void setName(type newName)
{
if ( condition )
{
name = newName;
}
else{
System.out.println(“asdfghjkjhgfdsa”)
}
}