torsdag 31 maj 2012

Arrays

Lektion 16 handlar bland annat om Arrayer.

An array is ordered and homogeneous. You are creating space for the object. An array is passed by reference (as an object) and NOT as a copie.

type[ ] name = new type[size];

There is a difference between acutal size (what you declare) and effective size (what you really are using).

Ex. asking the user for the values in the array
   int[ ] myArray = new int[5];
      for (int i = 0; i < 5; i++){
           myArray[i] = readInt("Value?:");
       }

Ex. Ask the user for the length of the array
  int maxLength = readInt("Max sixe of the array:");
  int[ ] myArray = new int [maxLength];

Ex. To keep track of where you are putting your values
   private static final int SENTINEL = -1;
   int numberOfScores = 0;
      for (int i = 0; i < maxLength; i ++){
         myArray[i] = readInt ("Next score:");
         if (myArray[i] == SENTINEL) break;
            numberOfScores++;