220 likes | 236 Views
Java Programming Arrays. Phil Tayco San Jose City College Slide version 1.0 November 20, 2018. Multiple Variables. Consider the following approach to finding the average of 3 values: double price1; double price2; double price3; // Code to get values from user
E N D
Java ProgrammingArrays Phil Tayco San Jose City College Slide version 1.0 November 20, 2018
Multiple Variables Consider the following approach to finding the average of 3 values: double price1; double price2; double price3; // Code to get values from user double average = (price1 + price2 + price3) / 3.0;
Multiple Variables This approach is simple enough, but what if we wanted to later change it finding the average of 5 values? Adding variables could be done double price1, price2, price3, price4, price5; // Code to get values from user double average = (price1 + price2 + price3 + price4 + price5) / 5.0; What challenges do you see happening with this approach?
Multiple Variables The main problem is extendibility Code could be written this way but adding variables and updating the code for performing calculations seems wasteful and limited What if we had an uncertain number of prices to get from the user? We would need to know how many we could possibly do and create variables for each potential price This is a common situation to see and with it, we can look at and take advantage of some patterns with the code
Multiple Variables doubleprice1; doubleprice2; doubleprice3; // Code to get values from user double average = (price1 + price2 + price3) / 3.0; The data type for all these variables are the same The intent of each variable is the same (each stores a “price”) Each price is distinguished by a number (the last number also representing the total number of potential price values to keep)
Arrays This common pattern of storing and managing data is best captured in a structure called an “array” Arrays are data structures that represent a collection of accessible common information By “common”, this means they have the same data type By “accessible”, this means we can get to and use the value of any variable in this structure at any time Arrays not only organize the data within your code, they also make code cleverly more effective and address those challenges mentioned earlier
Arrays To create an array, you must first declare it: double[] prices; The “[]” after the data type signifies that the variable “prices” will be an array The data type behind it declares that all elements in this array will be a double You can create an array of any data type (e.g. “int[] numbers” is an array integers) Once you declare an array, you must then define its capacity
Arrays double[] prices; prices = new double[100]; We’ve seen the “new” before as it represents creating a new object in memory In this case, the object is an array The [100] represents the capacity of the array – this tells the compiler to look for 100 places in memory next to each other where each element is designed to store a “double” At this point, “prices” will refer to the location of these 100 elements now reserved for us to use This reservation process is called “allocation”
Arrays At this point, we now have 100 variables created that we can freely use and access, all from 1 line of code Accessing any of them is easy, but comes with one very important concept to remember When referring to elements in a collection like this, we often say things like “the 1st element” or “the 3rd element” With arrays, we refer to locations in an array as array “index” numbers The special thing to remember is that the 1st element in an array is index 0 prices … 0.0 0.0 0.0 0.0
Arrays The reason why the first index is 0 as to do with memory locations and math that allows the code to very quickly find any element location The details can be discussed for another time, for introduction to arrays, the most important thing to remember is that the 1st element is at index 0 We can now make use of this the same way we would use regular variables With an array element, use the name of the array (“prices”) followed by specifying the index After that, you can treat that element like you would any other variable prices … 0.0 0.0 0.0 0.0 0 1 2 … 99
Arrays prices[0] = 2.4; prices[2] = 1.2; System.out.println(prices[0]); This may seem like added complication to organizing data, but the main advantage is in the use of the indexes Notice that referencing individual elements in the array is through a number (such as 0 and 2) This means you can also use an index like another variable prices … 2.4 0.0 1.2 0.0 0 1 2 … 99
Arrays int index = 1; prices[index] = 3.4; Compare this to the use of multiple variable names like price1 and price2 – those variables had to explicitly be called With an array, you can use these elements by managing the index variable This provides great flexibility in going through elements in an array (a.k.a. array “traversing”) Consider how you would initialize values in this prices array and set them all to -1.0 prices … 2.4 3.4 1.2 0.0 0 1 2 … 99
Arrays With separate variables, you need a line of code for each variable assignment With an array, you can do the same thing through the use of a loop for (int index = 0; index < 100; index++) prices[index] = -1.0; The index variable acts as a counter With each iteration, the appropriate element in the prices array is used The “100” used in the loop condition also happens to be the size of the array This pattern is often seen with for loops and arrays and can be used for other functions like calculating a sum
Arrays double sum = 0.0; for (int index = 0; index < 100; index++) sum += prices[index]; double average = sum / 100; The usage pattern of the loop for the array is the same with the main difference being the action taken inside the loop This style can be applied for other reasons to traverse an array such as printing all values Notice we also use the sum to calculate an average and that the denominator for the calculation is also the same as the array capacity The capacity of the array a value often use – in Java, this value is available as an object property
Arrays double sum = 0.0; for (int index = 0; index < prices.length; index++) sum += prices[index]; double average = sum / prices.length; “.length” can be used with any array you create It is a read-only property meaning you cannot assign a value directly to it This provides added flexibility in that we can now keep the code the same while changing the size of the array at the declaration
Arrays With using arrays, you do have to be careful of some common errors that can occur Most common is accidentally attempting to access element that has not been reserved for (int index = 0; index <= 100; index++) sum += prices[index]; The loop works fine until it gets to when index equals 100 At that point, the loop condition is still true (100 <= 100 is true) However, prices[100] does not exist (the 100th element is index 99)
Arrays This results in an “ArrayIndexOutOfBounds” exception error This error is also commonly known as an “off by 1” error and can occur in all programming languages where arrays are supported The tricky part is that the error is not found during compile time (the syntax is correct) The error occurs during run-time and also only occurs after the other parts of the array are correctly used This is what makes run-time errors challenging because they tend to occur unexpectedly and can make writing test cases difficult
Arrays Another challenge is distinguishing between array capacity versus “elements in use” Assuming all elements in prices is initialized to 0, after the first line, what is wrong with this code? double[] prices = new double[50]; prices[0] = 25.99; prices[1] = 12.99; prices[2] = 9.99; for (int index = 0; index < prices.length; index++) sum += prices[index]; double average = sum / prices.length;
Arrays The problem here is that there are 3 elements in use while we’ve reserved 50 array elements Storing up to 50 elements itself may be okay, but we are using the “.length” property to control the loop and calculate the average What is often needed in these cases is to have another variable that represents the number of active prices
Arrays double[] prices = new double[50]; prices[0] = 25.99; prices[1] = 12.99; prices[2] = 9.99; int numberOfPrices = 3; for (int index = 0; index < numberOfPrices; index++) sum += prices[index]; double average = sum / numberOfPrices; Such a variable adds flexibility in using the array but must also be remembered to manage in the code
Arrays Recall the dice tally program written earlier How would using arrays simplify this code? What changes can we make to provide additional capabilities?
Programming Exercise 8 Create a program maintains a maximum of 10 prices and allows the user to do the following: Enter a price Find the current total Find the average Find the minimum Find the maximum The prices must be maintained in an array of 10 elements When the user requests to enter a price, the program first makes sure there is enough space to add a new price value in the array – if there is not enough space, an error is presented and the program continues At any point, the user can do any of the “find” functions based on the amount of data entered