Arrays

Sometimes we might want to store a number of items of the same type, for example a set of chosen lottery numbers would consist of a list of 6 integers. To the unenlightened, we might write this as follows:

int firstNumber = 1;
int secondNumber = 2;
int thirdNumber = 4;
int fourthNumber = 8;
int fifthNumber = 16;
int sixthNumber = 32;
However Java (and most other languages) provide us with the ability to create a variable that holds a number of items - An Array. Consider this line of code which creates a variable to hold an array of ints:
int[] lottoNumbers = {1,2,4,8,16,32};
It is similar to the syntax we use to create a normal variable, except the the data type has [] appended to it, and the values are places in braces, separated by commas

We can do a similar thing for other data types, for example Strings:

String[] buildings = {"Sutton", "Ashton", "Dunham", "Hartford", "Sandfield"};

Arrays have a fixed capacity

When an array is created its size is determined, in the above example lottoNumbers it will have a capacity of 6, and buildings will have a capacity of 5.

Declaring an array without specifying its contents

Sometimes we may want to declare an array before we know what it's contents are (for example if we wanted to collect the values from the user). We can do this using the following syntax:

int[] intArray = new int[6];
Creating a new array in this format will set all six values to 0 (as it would for other number based data types). A String array would have a series of empty strings.

Accessing values in an array

Arrays are accessed by index (a number which represents their position in the array). Unlike conventional numbering, array positions start at 0. The first item in the above array could be accessed as such:

String libraryLocation = buildings[0]; //Sutton
and the fourth item could be accessed as follows:
String deptOfficeLocation = buildings[3]; //Hartford

Setting items in an array individually

We can set the value of an item in the same way we read them, by using an index position, for example:

String[] omniumRio2016 = new String[3];
omniumRio2016[0] = "Viviani";
omniumRio2016[1] = "Boudat";
omniumRio2016[2] = "Cavendish";

Array errors

If we try and access an item in an array using an index greater than or equal to the number of items in the array, an error will occur, for example the following code would cause the application to crash:

String[] jayZsProblems = new String[99];
//code to set Jay-Z's problems goes here...
String someProblem = jayZsProblems[100]; //this would fail
String anotherProblem = jayZsProblems[99]; //this would also fail
Remember that the item at the 99th index would actually be the 100th item (as it the index starts at 0). In the above examples case, the error you would see would be a java.lang.ArrayIndexOutOfBoundsException error. You would also get an error if you tried to set an item at a position that doesn't exist in the array

Strings and Character arrays

Because a String is just a sequence of characters, the String class helpfully provides us with a method to convert it to an Array of char elements. Thus we could create an array of characters holding the word 'hello' as follows:

String word = "Greetings";
char letters[] = word.toCharArray();;
We can also convert an Array of characters back to a String as follows:
char letters[] = {'h','e','l','l','o'};
String word = new String(letters);

Task

In a new command line application:

  1. Create an array with a capacity of 7, name it 'daysOfWeek'
  2. Accessing each element in turn, populate the array with the days of the week, starting with Monday
  3. Write code to access the element containing Wednesday and place it in a string variable.
  4. Print the variable's value to the console to make sure it is correct
  5. Using the code completion suggestions in IntelliJ IDEA, identify how to find the length of an array programmatically. Once you have done this, print the value corresponding to the length of the daysOfWeek array.

Task 2

  1. Using an Array literal, create an array with the contents being the names of each of the months of the year, in order
  2. Retrieve the 5th item in the array and store it in a variable
  3. Print the above variable. Verify it is 'May'
  4. Retrieve the item with index 11 in the array and store it in a variable, print the variable. Ensure it is 'December'
  5. Reusing the code that created the Array literal in the above steps, create a method that will take an integer as a variable, and return a String representing the month of the year that corresponds to that integer value, with 1 being January, and 12 being December
  6. Write a unit test to test that method

Task 3

Write a programme which will enable the user to enter a multiple choice question, four possible answers, and the number relating to the correct answer. The questions should be stored in a String variable, the four possible answers in an array of Strings, and the correct answer position in an int variable. At this point the programme should prompt the user to clear the console, and then press enter to proceed.

The programme should then re-print the question and four possible answers to the screen (labelled 1-4), and await input from the user. Once the user has typed a number, the programme should confirm if they are correct, and if not, print the correct answer out.