220 likes | 285 Views
Arrays Chapter 13. How to do the following with a one dimensional array: Declare it, use an index. In previous examples in the text data items (variables) were individual and isolated – except array lists. Often data is grouped into a collection of information
E N D
ArraysChapter 13 How to do the following with a one dimensional array: Declare it, use an index
In previous examples in the text data items (variables) were individual and isolated – except array lists. • Often data is grouped into a collection of information • Tables, telephone books, train time tables, bank statements • Called data structures
All information in a table related in some way • An array – table with a single row of information • 23 54 96 13 7 • ( an array of numbers) • John Paul George Ringo • ( an array of Strings) • In every array each item is known as an element, refered to by its position – called the index.
Each component, sometimes known as an element, subscript or index. • Arrays in Java start with the zeroth element • Indices not held in the computer – indeces are the way data in the computer are located • 23 54 96 13 7 32 the data • 0 1 2 3 4 5 the index
Array Operations • Creation - needs type, length • Put values in - initialize • Display - on screen • Search - locate values (data elements) • Calculate – add, subtract, divide etc.
Creating an Array • int [ ] ages = new int [6]; • String [ ] band = new String [4]; • Again indices start at zero, are integer, go up to one less than the length of the array • To input an integer element into the array ages • ages[2] = Integer.parseInt(textField.getText( )); • band[3] = textField.getText(); // gets element 3 of the band array
Output from an array • textField.setText (“ The first age is “ + Integer.toString (ages [0] ) ); textField.setText (“ The 4th band member is “ + band [3]; // remember start from zero! • Changing values in an array: • ages [3] = 99; // no longer 3 • band [2] = “Mike”; // no longer George
Using variables instead of numbers(numeric literals) in square [ ] brackets is what gives power to Java array handling • Example: computers sold in a store in one week • int [ ] sales = new int [7]; • Monday will be the zeroth element • sale[0] = 13; // 13 sold on Monday
Sale : 0 1 2 3 4 5 6 // index numbers • Data :13 8 22 17 24 15 23// data in array • Int sum; sum = sale[0] + sale[1] + sale[2]…sale[6]; • Loop using variable for index great tool • int sum = 0; • for ( int dayNumber = 0; dayNumber <= 6; dayNumber++) { sum = sum + • sale[ dayNumber ]; }
Each time the loop is repeated the next value is added to the total of the sales array. • The loop explicitly shows it is performing a systematic operation on an array
The index ‘dayNumber’ is clear and strongly related to the problem • The length of an array • int size; • size will be equal to the table.length • size = table.length; // .length is a special feature in Java. It holds the size of the array • Arrays are of a fixed size (length) once declared. Values of data within an aray may be changed and reused.
If new is used to redefine an array name all access to the old data is lost • given: int [ ] arry = { 1,2,3}; • int arry = new arry[ ]; // access to the data 1, 2 and 3 is lost.
Passing arrays as parametersThe name of the array holds the address of the zeroth element • private int sum ( int [ ] array) { • For ( int index = 0; index < = array.length; index++) { • total = total + array [ index]; } • return total; } • The header of the method declares an array named array in this case, of int type, the array can be of any length. It is general purpose and potentially very useful
Using constants • In programs that use several arrays, there are usually many loops, so various lengths might be needed: • int [ ] studentMark = new int [ ]; • int [ ] courseMark = new int [10]; • Given 10 is both the length of both studentMark and courseMark…but, what if 20 students are needed? To clarify the problem use ‘final’
final int students = 20;final int courses = 20; • Later … • int studentMark = new int [students]; • Int courseMark = new int [courses]; • for ( int index = 0; index < students; index++) { // body of loop … }
Initalizing an array • int [ ] table new int [10] ; • // an array (table) is set up and loaded with all zeros – all elements are set to 0. • Or all blanks for String arrays and • all nulls for arrays of objects. • An explicitly loaded array: ages loaded • int [ ]ages = { 23, 54, 96, 13, 7, 32 }; • // indexes: 0 1 2 3 4 5
String [ ] band = { “John” , “Paul” , “George”, “Ringo” }; • // loads names into the ‘band’ array • int [ ] table = new int [25]; • For ( int index = 0; index < table.length; index++) { table[index] = 0;} // loads all zeros into array ‘table’
A sample program page 249-250 • Holds an array rain. A display method used to output the days of the week and the rainfall values for each day. • a method Value (places a value into the array) • A largest method (finds the day with the most rainfall in the array) • private int [ ] rain = { 7, 8, 0, 4, 3, 8, 1 };
Rain methods • Lookup – given an array height we can extract to a: • double myHeight = height [25] ; • // the 25th element above the [0]th element • Given: name (an array of names of days of the week) dayName = name[dayNumber]; • Would return the String element referenced by dayNumber.
Searching: given two String arraysnames and numbers • A telephone directory can be created • for (index = 0;! ( names[index].equals (wanted) && ! (names[index].equals (“END”)); index++) { }; • if (names[index].equals (wanted)) • { nember.setText ( “Number is “ + numbers[index]) ; } • else {numbers.setText (“ Name not found “);}
Perform a serial search • Starts at beginning index 0 and continues to end of array. Each element is tested in turn. The telephone directory names could be in a file loaded into an array – searched as an array
Arrays of objectBalloon program pages 253-254 • A method changes size, increases the diameter of an Oval (the ‘balloon’) • Summary: • Array a collection of data • Given a name by programmer • All array items are of the same type • Declared: int [ ] array = new int [25]; • Index starts at zero • Largest index item 24 ( 0..24) for this example.