Arrays

OliverE

Power member.
Reputation
0
Arrays
An array is a container object that holds a fixed number of values of a single type.

* * * * *

Creating New Arrays
We are going to declare and initialise three arrays A, B and C all of length five. A and B are of type int and C is of type String.

The code we require is this;
[java]int A[] = new int[5];
int B[] = new int[5];
String C[] = new String[5];[/java]
5 Represents the length, int and string represents the type. And new tells the program we are creating the new arrays.

* * * * *

Adding to Arrays
If we wanted to add some content to the arrays we just structure the code as so;
[java]int A[] = new int[5];
int B[] = new int[5];
String C[] = {"The","Cat","Sat"};[/java]

* * * * *

Printing Elements in Arrays
Now you may be required to print out each element in your array. To do this we need to use a for loop to print out each element in the array;
[java]
int index;
String C[] = {"The","Cat","Sat"};

for(index=0; index; index++)
System.out.println(C[index]);[/java]
In this code, the index is how many times the for loop is executed, so where it says index, that mean it will print out 3 elements in the array.
The C[index] is basically telling the program which element to print out, as the for loop increments the value of index from 0<2, element 0 is 'The', 1 is 'Cat' and 2 is 'Sat'.

* * * * *

Finding the Longest Element
If you understand that then you might be required to print out which element in the string C is longest in length. I will have to modifiy my string as all elements are 3 chars in length;
[java]int index;
int maxlength = 0;
String longestelement = null;
String C[] = {"The","Monkey","Sat"};

for(index=0; index; index++)
if(C[index].length() > maxlength)
{
maxlength = C[index].length();
longestelement = C[index];
}
System.out.println(longestelement);[/java]
This code is a step up from the previous one, it basically uses the for loop to ask the program if the length of the element is longer than the length of the previous element. If it is, then the 'longestelement' is stored in the longestelement variable, which is then printed at the end of the program.

* * * * *

Thats it for arrays, let me know if you need some help.
 
Great tutorial, Bleeps! I find the syntax for Java to be kind of annoying and strict, or maybe I am just used to PHP, but this helped! Thanks!
 
Cookies are required to use this site. You must accept them to continue using the site. Learn more…