Download presentation
Presentation is loading. Please wait.
Published byKelley Barton Modified over 9 years ago
1
1 Intro to Programming & Algorithm Design Arrays Copyright 2003 by Janson Industries This presentation can be viewed on line in a file named: ch08.IntrotoProg.Arrays.ppt Assg
2
Copyright 2014 by Janson Industries 2 Objectives n Explain u Arrays u Advantages of arrays u How to process arrays u Parallel arrays u Multi-dimensional arrays n Show how to implement arrays in Java
3
Copyright 2014 by Janson Industries 3 Array n A programming data structure that holds multiple values u Think of it as a single row of data n Array values u Must all be of the same type F An array of strings, or an array of integers, or an array of… F Can't have an array that has both strings and integers and… u Individual values are referred to by an index (or subscript) F The index begins at 0
4
Copyright 2014 by Janson Industries 4 Array n Arrays are fixed in length u Arrays have a size - the max number of values they can hold n An array is assigned a name n Array values can be: u Constant F Fixed values for program use Discount rates, zip codes u Variable F Multiple user or file input values Shopping cart items
5
Copyright 2014 by Janson Industries 5 Array n When creating, specify u The type of values it will hold u The maximum number of values it will hold u A name n To indicate this in pseudocode and flowcharts u Specify the value type first u Then the name u [maximum number of values] F Declare Integer itemCosts[7] F Declare String stateAbbrs[4]
6
Copyright 2014 by Janson Industries 6 Array n Can use a variable to define size u Instead of a fixed constant n Especially useful for multiple arrays holding related data u Lists of items for sale, descriptions, and prices n If number of items for sale changes, just change arraySize and all arrays changed Declare Integer arraySize = 4 Declare String stateAbbrs[arraySize ]
7
Copyright 2014 by Janson Industries 7 Array n String stateAbbrs[4] results in n To refer to a particular value, use the variable name and index number in brackets n stateAbbrs[2] = "FL" results in Index 0 1 2 3 FL
8
Copyright 2014 by Janson Industries 8 Array n Let's be clear: u stateAbbrs[2] = "FL" results in data be put into the third position of the array u stateAbbrs[4] = "GA" results in? Index 0 1 2 3 FL An out of bounds error!
9
Copyright 2014 by Janson Industries Array Advantages n Great for storing lists of data u Instead of defining many variables to hold data use one array n Easy to process array data in a loop u Another good reason to use a size variable n As mentioned, can assign data in program or read data from keyboard/file and assign to array 9
10
Copyright 2014 by Janson Industries Using Arrays n A pizza parlor application will accept orders for delivery n Only deliver to certain zip codes n Will build an array with valid zip codes of F 32246 F 32224 F 32250 n Will ask user for zip code, read it, and read array to confirm it is valid 10
11
Copyright 2014 by Janson Industries Using Arrays n If the zip code is valid, display the text Great, we can deliver to you! n If not then, Sorry, we can't deliver to you. n In class assg: u Create the pseudo code or flow chart to do this 11
12
Copyright 2014 by Janson Industries Using Arrays 12 Module main() Declare String zipCode, validZipCode[3] validZipCode[0] = "32246" validZipCode[1] = "32224" validZipCode[2] = "32250" Display "What is your zip code?" Input zipCode n A little harder than you thought? n This initializes the array, displays the prompt and reads the zip
13
Copyright 2014 by Janson Industries Using Arrays 13 Boolean isZipCodeValid = false For ctr = 0 to 2 If zipCode = validZipCode[ctr] Then isZipCodeValid = true End If End For If isZipCodeValid = true Then Display "Great, we can deliver to you!" Else Display "Sorry, we can't deliver to you." End If End Module n Need to keep track if zip is valid or not: n isZipCodeValid
14
Copyright 2014 by Janson Industries 14 Using Arrays - SFC
15
Copyright 2014 by Janson Industries Using Arrays - SFC 15
16
Copyright 2014 by Janson Industries Using Arrays in Raptor 16 n A Raptor array index starts at 1 n String stateAbbrs[4] results in n Also, if you enter a zip code (32246) Raptor assumes it is a number u Must engage in some "tom foolery" to get it to work right Index 1 2 3 4
17
Copyright 2014 by Janson Industries Using Arrays Raptor 17 When zipCode read we concatenate an "s" to make it a String and assign to stringZipCode
18
Copyright 2014 by Janson Industries Using Arrays Raptor 18 In the validity check, we concatenate an "s" to the value in the array and compare to stringZipCode
19
Copyright 2014 by Janson Industries Using Arrays Raptor 19 Notice that the user has no idea about the concatenation and that the data is pure. I.e. we could have put the zip codes in the array with the "s" but this would have "polluted" the data
20
Copyright 2014 by Janson Industries Using Arrays Raptor 20
21
Copyright 2014 by Janson Industries Using Arrays In Java 21 n Syntax to create similar to pseudocode n new type[size] n new String[3] n new int[3] n However, must create an array variable and assign array to it n type[] name = new type[size] n String[] zipCodes = new String[3]; n int[] qtys = new int[3];
22
Copyright 2014 by Janson Industries n Lets look at this closer: n String[] zipCodes = new String[3] ; Using Arrays In Java 22 Creates a String array of size 3 1 Creates a Sting array variable named zipCodes 2 Assigns the String array to zipCodes (the String array variable) 3
23
Copyright 2014 by Janson Industries Using Arrays In Java 23 n Syntax to create similar to pseudocode n new type[size]; n new String[3]; n new int[3]; n However, must create an array variable and assign array to it n type[] name = new type[size]; n String[] zipCodes = new String[3]; n int[] qtys = new int[3];
24
Copyright 2014 by Janson Industries Using Arrays In Java 24 None of the Raptor Tom Foolery needed
25
Copyright 2014 by Janson Industries Using Arrays In Java 25
26
Copyright 2014 by Janson Industries 26 Why Arrays? n Could have done the same thing with this n Why use the array? If zipCode ="32246" Then isZipCodeValid = true Else If zipCode ="32224" Then isZipCodeValid = true Else If zipCode ="32250" Then isZipCodeValid = true End If
27
Copyright 2014 by Janson Industries 27 Why Arrays? n There really wasn't a lot less code using the array n But what happens if the delivery area expands to 6 zip codes? Declare String validZipCode[3] validZipCode[0] = "32246" validZipCode[1] = "32224" validZipCode[2] = "32250" For ctr = 0 to 2 If zipCode = validZipCode[ctr] Then isZipCodeValid = true End If End For
28
Copyright 2014 by Janson Industries 28 Why Arrays? n The if logic keeps expanding n With the array: u Change the size of the array u Add an initialization statement for each new value u Change the for statement sentinel value n And if instead of hard coding the array size, we had created a variable to hold the size…
29
Copyright 2014 by Janson Industries 29 Why Arrays? n …we never have to change the for statement or size of array n And the for works for any number of zip codes Declare Integer arraySize = 6 Declare String validZipCode[arraySize] validZipCode[0] = "32246" validZipCode[1] = "32224" validZipCode[2] = "32250" validZipCode[3] = "32252" validZipCode[4] = "32244" validZipCode[5] = "32228" For ctr = 0 to (arraySize -1) If zipCode = validZipCode[ctr] Then isZipCodeValid = true End If End For Note sentinel value in For
30
Copyright 2014 by Janson Industries Using Arrays Efficiently n Using a For loop is inefficient u Will always loop the number of times of the array size n We want to stop looping as soon as we find a match n So we'll change the loop to a while with a compound condition 30
31
Copyright 2014 by Janson Industries Using While to Search 31 Module main() Integer arraySize = 6 Integer ctr = 0 String validZipCode[arraySize], zipCode Boolean isZipCodeValid = false validZipCode[0] = "32246" validZipCode[1] = "32224" validZipCode[2] = "32250" validZipCode[3] = "32252" validZipCode[4] = "32244" validZipCode[5] = "32228" Display "What is your zip code?" Input zipCode
32
Copyright 2014 by Janson Industries Using Arrays 32 While (ctr < arraySize AND isZipCodeValid = false) If zipCode = validZipCode[ctr] Then isZipCodeValid = true End If ctr = ctr + 1 End While If isZipCodeValid = true Then Display "Great, we can deliver to you!" Else Display "Sorry, we can't deliver to you." End Module
33
Copyright 2014 by Janson Industries Using Arrays SFC 33
34
Copyright 2014 by Janson Industries Using Arrays SFC 34
35
Copyright 2014 by Janson Industries Using Arrays Raptor 35
36
Copyright 2014 by Janson Industries Using Arrays Raptor 36 Notice the argument needed to work in Raptor
37
Copyright 2014 by Janson Industries Using Arrays Raptor 37
38
Copyright 2014 by Janson Industries import java.util.Scanner; public class ArrayPgmWhile { // Variables and objects needed to read from command line static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { // Variables and objects needed to hold input, intermediate values, and results int arraySize = 6; int ctr = 0; String[] validZipCode = new String[arraySize]; String zipCode =""; Boolean isZipCodeValid = false; // Initialize the array with valid zip codes validZipCode[0] = "32246"; validZipCode[1] = "32224"; validZipCode[2] = "32250"; validZipCode[3] = "32252"; validZipCode[4] = "32244"; validZipCode[5] = "32228"; //Prints out a blank line and prompt System.out.println(" "); System.out.print("What is your zip code? "); 38 Using Arrays Java
39
Copyright 2014 by Janson Industries //Read the zip zipCode = keyboard.nextLine(); //Check the array while (ctr < arraySize && isZipCodeValid == false) { if (zipCode.equals(validZipCode[ctr])) { isZipCodeValid = true; } ctr = ctr + 1; } //Tell user whether we can deliver or not System.out.println(" "); if (isZipCodeValid) { System.out.print("Great, we can deliver to you!"); }else{ System.out.print("Sorry, we can't deliver to you."); } //End of method } //End of class } 39 Using Arrays Java Notice the argument needed to work in Java
40
Copyright 2014 by Janson Industries Using Arrays Java 40
41
Copyright 2014 by Janson Industries Using Arrays n The app is so popular, customer now wants it to accept orders n So if zip code is valid u Accept up to 3 order items u Store in array u Display all items at end n Need u New array to hold info u Loop to load array u Loop to display array contents 41
42
Copyright 2014 by Janson Industries Using Arrays n Better do an external design (XD) of new app so we can be sure of what the user wants 42 What is your zip code? 33333 Sorry, we can't deliver to you. What is your zip code? 32228 Enter what would you like or Done Pepperoni pizza Enter what would you like or Done Diet soda Enter what would you like or Done done This is what you have ordered: Pepperoni pizza Diet soda
43
Copyright 2014 by Janson Industries 43 Validate customer When array maxed, items displayed When "done" entered, items displayed Arrays
44
Copyright 2014 by Janson Industries Display Items Compare To List Using Arrays n Better do an internal design and modularize 44 main Validate Customer Get Order Items Display Order Validate Zip Code Display invalid message Read Items Create Valid List Ask For Zip
45
Copyright 2014 by Janson Industries Display Items Compare To List Using Arrays n Define method calls 45 main() validate Cust() getOrder() show Order() Validate Zip Code Display invalid message Read Items Create Valid List Ask For Zip
46
Copyright 2014 by Janson Industries n validateCust() needs to return a Boolean value to main indicating if the zip code is valid or not n If valid, main calls getOrder and showOrder n Because getOrder and showOrder use orderArray, make orderArray and orderArraySize static global variables n Global variables are defined within the class but not in a method n Change name of application to OrderEntry Using Method Calls 46
47
Copyright 2014 by Janson Industries n Because the user is entering data, the array may not have values in every index location n Don't want to process empty locations n Two ways to handle: n Check for an empty value n Keep track of how many values are entered n Put a sentinel value in the location after the last valid value Partially Filled Arrays 47
48
Copyright 2014 by Janson Industries Pseudocode 48 n Main() logic greatly simplified Declare Integer orderArraySize = 3 Declare String orderArray[orderArraySize] Module main() Declare Boolean isCustValid isCustValid = validateCust() If(isCustValid) Then getOrder() showOrder() End If End Module
49
Copyright 2014 by Janson Industries Pseudocode 49 n Alternative way to define and initialize an array Declare Integer arraySize = 4 Declare String stoogesArray[arraySize] = "Moe", "Larry", "Curly", "Shemp"
50
Copyright 2014 by Janson Industries Pseudocode 50 Module Boolean validateCust() Integer ctr = 0 Boolean isZipCodeValid = false Integer zipCodeArraySize = 6 String validZipCode[zipCodeArraySize] = "32246", "32224", "32250", "32252", "32244", "32228" String zipCode Display "What is your zip code?" Input zipCode
51
Copyright 2014 by Janson Industries Pseudocode 51 While (ctr < zipCodeArraySize AND isZipCodeValid = false) If zipCode = validZipCode[ctr] Then isZipCodeValid = true End If ctr = ctr + 1 End While If isZipCodeValid = false Then Display "Sorry, we can't deliver to you." End If return isZipCodeValid End Module
52
Copyright 2014 by Janson Industries Pseudocode 52 Module void getOrder() Integer ctr = 0 String item Do Display "Enter what would you like or Done" Input item If item <> "Done" Then orderArray[ctr] = item ctr = ctr + 1 End If While (ctr "Done") End Module n Always want to prompt for an item so a do while is used
53
Copyright 2014 by Janson Industries Pseudocode 53 n Uses a while to show array contents and checks for a blank entry to know when to quit Module void showOrder() Integer ctr = 0 Display "This is what you have ordered:" While (ctr < orderArraySize AND orderArray[ctr] <> "") Display orderArray[ctr] ctr = ctr + 1 End While End Module
54
Copyright 2014 by Janson Industries 54 SFC - OrderEntry Global variables defined main line logic
55
Copyright 2014 by Janson Industries 55 SFC OrderEntry main line logic
56
Copyright 2014 by Janson Industries 56 validateCust() SFC - OrderEntry
57
Copyright 2014 by Janson Industries 57 validateCust() SFC OrderEntry
58
Copyright 2014 by Janson Industries 58 getOrder() SFC - OrderEntry
59
Copyright 2014 by Janson Industries 59 getOrder() SFC - OrderEntry
60
Copyright 2014 by Janson Industries 60 showOrder() SFC OrderEntry
61
Copyright 2014 by Janson Industries 61 Raptor OrderEntry main() Have to initialize orderArray to nulls ("")
62
Copyright 2014 by Janson Industries 62 validateCustomer() Raptor OrderEntry All the old zip code validation code is here (don't forget Raptor arrays start at 1 not 0)
63
Copyright 2014 by Janson Industries 63 Raptor OrderEntry validateCustomer()
64
Copyright 2014 by Janson Industries 64 getOrder() Raptor OrderEntry
65
Copyright 2014 by Janson Industries 65 showOrder() Raptor OrderEntry Check for null value to see when to stop
66
Copyright 2014 by Janson Industries 66 When run Raptor OrderEntry
67
Copyright 2014 by Janson Industries 67 n Alternative way to define and initialize an array u Don't specify a size for the array u Instead of explicitly creating an array object, supply values F Surrounded with {} F Separated by commas Java String stoogesArray[] = {"Moe", "Larry", "Curley", "Shemp"};
68
Copyright 2014 by Janson Industries 68 n Have the pseudocode and flowcharts adequately defined what the application should do? u I hope you said yes! import java.util.Scanner; public class OrderEntry { // Variables and objects needed to read from command line static Scanner keyboard = new Scanner(System.in); // Global variables and objects static int orderArraySize = 3; static String[] orderArray = new String[orderArraySize]; // Checks that zip code is deliverable private static boolean validateCust(){ // Variables and objects needed to hold input and processing status String zipCode =""; Boolean isZipCodeValid = false; Java OrderEntry validateCustomer()
69
Copyright 2014 by Janson Industries 69 // Variables and objects needed to hold valid zip codes int zipCodeArraySize = 6; // Create and initialize the array with valid zip codes String[] validZipCode = {"32246", "32224", "32250", "32252", "32244", "32228"} ; // Prints out a blank line and user prompt System.out.println(" "); System.out.print("What is your zip code? "); // Read the zip zipCode = keyboard.nextLine(); // Check the array to validate the entered zip code int ctr = 0; while (ctr < zipCodeArraySize && isZipCodeValid == false) {if (zipCode.equals(validZipCode[ctr])) { isZipCodeValid = true; } ctr++; } // Possibly displays invalid message if (isZipCodeValid == false) { System.out.print("Sorry, we can't deliver to you.") } System.out.println(" "); // Returns whether zip was valid or not return isZipCodeValid; }
70
Copyright 2014 by Janson Industries 70 // Prompts user for order items and stores in orderArray private static void getOrder(){ // Variables and objects needed to store order items String item = ""; // Prompt for and read order items then store in an array. int ctr = 0; do { System.out.print("Enter what would you like or Done "); item = keyboard.nextLine(); if (!item.equalsIgnoreCase("Done")) { orderArray[ctr] = item; ctr++; } System.out.println(" "); } while (ctr < orderArraySize && !item.equalsIgnoreCase("Done")); } Java OrderEntry getOrder() Notice use of equalsIgnoreCase()
71
Copyright 2014 by Janson Industries 71 // Displays ordered items private static void showOrder(){ int ctr = 0; System.out.println("This is what you have ordered:"); while (ctr < orderArraySize && !(orderArray[ctr] == null)){ System.out.println(orderArray[ctr]); ctr++; } public static void main(String[] args) { //Variable to hold customer status Boolean isCustValid = false; isCustValid = OrderEntry.validateCust(); if (isCustValid){ OrderEntry.getOrder(); OrderEntry.showOrder(); } //End of method } //End of class } Vastly simplified main() Java OrderEntry showOrder()
72
Copyright 2014 by Janson Industries 72 showOrder() Java OrderEntry
73
Copyright 2014 by Janson Industries 73 Passing Arrays n Just like strings and numbers, arrays can be passed and returned from methods u Syntax pretty much the same u To pass a string array F methodName(arrayVariableName) u To return a string array F in header: String[] methodName F at method end: return arrayVariableName n Arrays make passing many or a variable number of values easier
74
Copyright 2014 by Janson Industries 74 Passing Arrays n Instead of making orderArray a global variable, have u getOrder create orderArray & return it u showOrder will have orderArray passed to it n Must change u Both methods headers u getOrder needs a return statement u main creates an array variable, assigns orderArray (returned by getOrder) to it, passes it to showOrder
75
Copyright 2014 by Janson Industries Passing Arrays Pseudocode 75 Declare Integer orderArraySize = 3 Module main() Declare String orderArray[orderArraySize] Declare Boolean isCustValid isCustValid = validateCust() If(isCustValid) Then orderArray[] = getOrder() showOrder(orderArray[] ) End If End Module orderArray not a global variable n Main creates variable, assigns the array returned by getOrder to it, passes it to showOrder
76
Copyright 2014 by Janson Industries No Changes to validateCust 76 Module Boolean validateCust() Integer ctr = 0 Boolean isZipCodeValid = false Integer zipCodeArraySize = 6 String validZipCode[zipCodeArraySize] = "32246", "32224", "32250", "32252", "32244", "32228" String zipCode Display "What is your zip code?" Input zipCode
77
Copyright 2014 by Janson Industries No Changes to validateCust 77 While (ctr < zipCodeArraySize AND isZipCodeValid = false) if zipCode = validZipCode[ctr] then isZipCodeValid = true End If ctr = ctr + 1 End While if isZipCodeValid = false then Display "Sorry, we can't deliver to you." End If return isZipCodeValid End Module
78
Copyright 2014 by Janson Industries Passing Arrays Pseudocode 78 Module String[] getOrder() Integer ctr = 0 String item, orderArray[orderArraySize] Do Display "Enter what would you like or Done" Input item If item <> "Done" Then orderArray[ctr] = item ctr = ctr + 1 End If While (ctr "Done") Return orderArray End Module n Change method header to return array, create and return orderArray
79
Copyright 2014 by Janson Industries Passing Arrays Pseudocode 79 n Change header to accept orderArray Module void showOrder(String orderArray[]) Integer ctr = 0 Display "This is what you have ordered:" While (ctr < orderArraySize AND orderArray[ctr] <> "") Display orderArray[ctr] ctr = ctr + 1 End While End Module
80
Copyright 2012 by Janson Industries 80 private static String[] getOrder(){ //Variables and objects needed to store order items String item = ""; String[] orderArray = new String[orderArraySize]; //Variables and objects needed to read from command line : : : Same code as before : : : return orderArray; //End of method } public class OrderEntryPassArray { //Global variables and objects static int orderArraySize = 3; private static boolean validateCust(){ : : : Same code as before : : : orderArray no longer a global variable A String array will be returned orderArray is a local variable orderArray is returned Passing Arrays Java
81
Copyright 2012 by Janson Industries 81 private static void showOrder(String[] orderArray) { int ctr = 0; // Displays order items System.out.println("This is what you have ordered:"); while (ctr < orderArraySize && !(orderArray[ctr] == null)) { System.out.println(orderArray[ctr]); ctr++; } // End of method } public static void main(String[] args) { //Variables to hold customer status and orders Boolean isCustValid = false; String[] orderArray; isCustValid = OrderEntryPassArray.validateCust(); if (isCustValid){ //If valid invokes getOrder and receives orderArray orderArray = OrderEntryPassArray.getOrder(); //Invokes showOrder and passes orderArray to the method OrderEntryPassArray.showOrder(orderArray); } //End of method } showOrder accepts a String array main has a local String array variable main gets the order array and passes it to showOrder
82
Copyright 2012 by Janson Industries 82 Still works correctly
83
Copyright 2014 by Janson Industries 83 Processing An Array n How can you find the following for the values in an array u Largest u Smallest u Total u Average
84
Copyright 2014 by Janson Industries 84 Processing An Array n Say you have an array of test scores u Create a variable to hold the largest value u Read the first value and set it as the largest u Then loop through the remaining values and compare each to the largest F If new value larger, set largest value to it
85
Copyright 2014 by Janson Industries 85 Processing An Array Declare Integer largestValue, ctr = 1 largestValue = testScoresArray[0] While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") If testScoresArray[ctr] > largestValue Then largestValue = testScoresArray[ctr] End If ctr = ctr + 1 End While n Finding the largest value
86
Copyright 2014 by Janson Industries 86 Processing An Array Declare Integer smallestValue, ctr = 1 smallestValue = testScoresArray[0] While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") If testScoresArray[ctr] < smallestValue Then smallestValue = testScoresArray[ctr] End If ctr = ctr + 1 End While n Finding the smallest value u Very similar to largest search
87
Copyright 2014 by Janson Industries n Finding the sum 87 Processing An Array Declare Integer sumValue, ctr = 0 While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") sumValue = sumValue + testScoresArray[ctr] ctr = ctr + 1 End While
88
Copyright 2014 by Janson Industries n Finding the average u Have to find the sum then divide by the number of values F Which we have kept track of with ctr 88 Processing An Array Declare Integer sumValue, avgValue, ctr = 0 While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") sumValue = sumValue + testScoresArray[ctr] ctr = ctr + 1 End While avgValue = sumValue/ctr
89
Copyright 2014 by Janson Industries n Will have main() perform all the calculations n Will have two other methods u initializeScoreTestArray() F Loads the scores u displayValues() F shows the scores and calculated values 89 Processing An Array - Raptor
90
Copyright 2014 by Janson Industries 90 Processing An Array - Raptor initializeTestScoreArray()
91
Copyright 2014 by Janson Industries 91 Processing An Array - Raptor displayValues() Loop to show individual scores
92
Copyright 2014 by Janson Industries 92 Processing An Array - Raptor displayValues() Puts out a blank line then the four calculated values
93
Copyright 2014 by Janson Industries 93 Processing An Array - Raptor main() Initialize the scores Set ctr to the 2nd test score because… … we capture the first test score with these variables Loop from 2 until ctr = 6 Calc the sum
94
Copyright 2014 by Janson Industries 94 Processing An Array - Raptor main() Checks the array for smaller and larger values Calcs average and calls display module (notice ctr-1 in avg calc)
95
Copyright 2014 by Janson Industries 95 Processing An Array - Raptor Results
96
Copyright 2014 by Janson Industries 96 Parallel Arrays n Use more than one array to store many pieces of related information n Related info stored in same relative position in each array n For instance storing employee information like u Name u Address u Phone number
97
Copyright 2014 by Janson Industries 97 Parallel Arrays n For 3 employees with the following info: u Joe lives at 1 Main St. and has a phone number of 111-1111 u Mary lives at 2 Oak St. and has a phone number of 222-2222 u Pam lives at 1 Elm St. and has a phone number of 333-3333
98
Copyright 2014 by Janson Industries 98 Parallel Arrays n Done with the following 3 arrays n Name array n Address array n Phone array Joe 1 Main St. 111- 1111 Mary 2 Oak St. 222- 2222 333- 3333 3 Elm St. Pam
99
Copyright 2014 by Janson Industries 99 Parallel Arrays n Change OrderEntry to accept a quantity for each item u User will enter a qty for each order item u Qty will be saved in qtyArray u Accumulate total number of items u Change message to say F The following are the XX items you have ordered F Have the qty before each item F If qty > 1, add an "s" to item (make item plural)
100
Copyright 2014 by Janson Industries 100 Parallel Arrays n So when an item is entered n It's qty is entered in the same position in the qtyArray pizza 6
101
Copyright 2014 by Janson Industries 101 Parallel Arrays n Because getOrder creates two arrays must make the array variables global n Why? u Java methods can only return a single variable F No way to return 2 array variables
102
Copyright 2014 by Janson Industries 102 Parallel Arrays n getOrder will u Display the new text u Populate both arrays with values u Calculate and return the total number of items n main will get the total and pass to showOrder n showOrder will receive the total and display the new text
103
Copyright 2014 by Janson Industries Parallel Arrays n Here’s the external design of changes to application 103 What is your zip code? 33333 Sorry, we can't deliver to you. What is your zip code? 32228 Enter what would you like or Done Pepperoni pizza How many Pepperoni pizzas would you like 6 Enter what would you like or Done Small diet cola How many Small diet colas would you like 1 Enter what would you like or Done Large calzone How many Large calzones would you like 5 The following are the 12 items you have ordered: 6 Pepperoni pizzas 1 Small diet cola 5 Large calzones Notice "s" on items with qty >1
104
Copyright 2014 by Janson Industries Passing Arrays Pseudocode 104 Declare Integer orderArraySize = 3 Declare String orderArray[orderArraySize] Declare String qtyArray[orderArraySize] Module main() Declare Boolean isCustValid Integer total isCustValid = validateCust() If(isCustValid) Then total = getOrder() showOrder(total) End If End Module orderArray & qtyArray are global parallel arrays New variable total passed
105
Copyright 2014 by Janson Industries No Changes to validateCust 105 Module Boolean validateCust() Integer ctr = 0 Boolean isZipCodeValid = false Integer zipCodeArraySize = 6 String validZipCode[zipCodeArraySize] = "32246", "32224", "32250", "32252", "32244", "32228" String zipCode Display "What is your zip code?" Input zipCode
106
Copyright 2014 by Janson Industries No Changes to validateCust 106 While (ctr < zipCodeArraySize AND isZipCodeValid = false) if zipCode = validZipCode[ctr] then isZipCodeValid = true End If ctr = ctr + 1 End While if isZipCodeValid = false then Display "Sorry, we can't deliver to you." End If return isZipCodeValid End Module
107
Copyright 2014 by Janson Industries Passing Arrays Pseudocode 107 Module String[] getOrder() Integer ctr = 0, totalQty String item, qty Do Display "Enter what would you like or Done" Input item If item <> "Done" Then orderArray[ctr] = item Display “How many “, item, “s would you like“ Input qty qtyArray[ctr] = qty totalQty = totalQty + qty ctr = ctr + 1 End If While (ctr "Done") Return totalQty End Module n New variables to hold qty info Setting parallel arrays' values
108
Copyright 2014 by Janson Industries Passing Arrays Pseudocode 108 Module void showOrder(Integer totalQty) Integer ctr = 0 Display “The following are the “, totalQty, “ items you have ordered” While (ctr < orderArraySize AND orderArray[ctr] <> "") Display qtyArray[ctr], " ", orderArray[ctr] If (qtyArray[ctr] > 1) Display “s” End If ctr = ctr + 1 End While End Module Displaying item and qty info Make item plural
109
Copyright 2014 by Janson Industries Passing Arrays Raptor 109 Just declared some new variables No changes to validateCustomer
110
Copyright 2014 by Janson Industries Passing Arrays Raptor 110 Declare the new qty variables Initialize totalQty
111
Copyright 2014 by Janson Industries 111 Get qty info, load into array Calc totalQty
112
Copyright 2014 by Janson Industries Passing Arrays Raptor 112 New msg variable needed to pluralize item Make msg plural Build msg with qty and item Display total items
113
Copyright 2014 by Janson Industries private static int getOrder(){ //Variables and objects needed to store order items String item = ""; String qty = ""; int totalQty = 0; //Variables and objects needed to read from command line : : : if (!item.equalsIgnoreCase("Done")) { orderArray[ctr] = item; System.out.print("How many " + item +"s would you like "); try { qty = dataIn.readLine(); qtyArray[ctr] = qty; totalQty = totalQty + Integer.parseInt(qty); } catch (IOException e) { e.printStackTrace(); } ctr++; } : : : return totalQty; 113 public class ParallelArrays { //Global variables and objects static int orderArraySize = 3; static String[] orderArray = new String[orderArraySize]; static String[] qtyArray = new String[orderArraySize]; : : : New qtyArray and global variable New qty and totalQty variables Get qty only if not done Load qtyArray and accumulate totalQty Return totalQty
114
Copyright 2014 by Janson Industries 114 private static void showOrder(int totalQty){ int ctr = 0; //Displays order items System.out.println("The following are the " + totalQty + " items you have ordered"); while (ctr < orderArraySize && !(orderArray[ctr] == null)){ System.out.print(qtyArray[ctr] + " "); System.out.print(orderArray[ctr]); if (Integer.parseInt(qtyArray[ctr]) > 1) { System.out.println("s");} else {System.out.println(" ");} ctr++; } //End of method } public static void main(String[] args) { // Variable to hold customer status Boolean isCustValid = false; int totalQty = 0; isCustValid = ParallelArrays.validateCust(); if (isCustValid){ totalQty = ParallelArrays.getOrder(); ParallelArrays.showOrder(totalQty); } // End of method showOrder accepts totalQty main has a totalQty variable Gets totalQty and passes New message with totalQty Prints qty and item If more than one, adds an "s"
115
Copyright 2014 by Janson Industries 115 Notice the total and individual amounts Prompts for items & amounts
116
Copyright 2014 by Janson Industries 116 Parallel Arrays - Finding a Range n Store the upper or lower limit of each range in the array n Compare value to limit n If (depending on whether upper of lower limit) you have found the correct range n Example assigning a letter grade to a numeric grade u 99 entered, A returned
117
Copyright 2014 by Janson Industries 117 Finding a Range n Our ranges for the letter grades will be u F < 64.5 u D < 69.5 u C < 79.5 u B < 89.5 u A < 100.5
118
Copyright 2014 by Janson Industries Parallel Arrays n Will create two parallel arrays to hold the grades and limits n gradeArray n rangeArray A B C 100.589.5 79.5 DF 64.569.5
119
Copyright 2014 by Janson Industries 119 Finding a Range n When user enters a numeric grade will compare it to the first value in the rangeArray[] u If entered grade less than 64.5 we have found the correct position in the array F Display the letter grade in the same location of the gradeArray u Else compare to next location in rangeArray, etc.
120
Copyright 2014 by Janson Industries Finding a Range 120 Module main() Integer arraySize = 5 String gradeArray[arraySize] Real rangeArray[arraySize] gradeArray[0] = "F" gradeArray[1] = "D" gradeArray[2] = "C" gradeArray[3] = "B" gradeArray[4] = "A" rangeArray[0] = 64.5 rangeArray[1] = 69.5 rangeArray[2] = 79.5 rangeArray[3] = 89.5 rangeArray[4] = 100.5
121
Copyright 2014 by Janson Industries 121 Integer ctr = 0 Integer numericGrade = 0 Boolean isGradeAssigned = false Display " " Display "What is the numeric grade? " Input numericGrade While (ctr < arraySize AND isGradeAssigned = false) If (numericGrade < rangeArray[ctr]) then isGradeAssigned = true Else ctr = ctr + 1; End If End While Display " " Display "A numeric grade of ", numericGrade, " is equal to a letter grade of ", gradeArray[ctr]); End Module Finding a Range
122
Copyright 2014 by Janson Industries Finding a Range Raptor 122 Initialize the arrays
123
Copyright 2014 by Janson Industries Finding a Range Raptor 123 Notice how loop condition changed Initialize the other variables
124
Copyright 2014 by Janson Industries Finding a Range - Raptor 124
125
Copyright 2010 by Janson Industries 125 import java.util.Scanner; public class LetterGrade { // Variables and objects needed to read from command line static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { // Variable to hold array sizes int arraySize = 5; // Arrays to hold grade and ranges String[] gradeArray = new String[arraySize]; double[] rangeArray = new double[arraySize]; // Initialize the array with letter grades gradeArray[0] = "F"; gradeArray[1] = "D"; gradeArray[2] = "C"; gradeArray[3] = "B"; gradeArray[4] = "A"; // Initialize the array with grade range upper limit rangeArray[0] = 64.5; rangeArray[1] = 69.5; rangeArray[2] = 79.5; rangeArray[3] = 89.5; rangeArray[4] = 100.5; Java Range Search
126
Copyright 2010 by Janson Industries 126 // Loop control variables int ctr = 0; Boolean isGradeAssigned = false; // Variable to hold input values double numericGradeDouble = 0; // Prints out a blank line and instruction System.out.println(" "); System.out.print("What is the numeric grade? "); // Read the numeric grade numericGradeDouble = keyboard.nextDouble(); // Search the array to find the correct range while (ctr < arraySize && isGradeAssigned == false) { if (numericGradeDouble < rangeArray[ctr]) { isGradeAssigned = true; } else { ctr++; } System.out.println(" "); System.out.print("A numeric grade of " + numericGradeString + " is equal to a letter grade of " + gradeArray[ctr]); // End of method } // End of class } If range found, no need to increase loop counter
127
Copyright 2010 by Janson Industries 127
128
Copyright 2014 by Janson Industries 128 Multidimensional Arrays n Arrays don't have to consist of a single row n A multi-row index is a two dimensional array. Examples: u A spreadsheet table u An egg carton u Pill box
129
Copyright 2014 by Janson Industries 129 Multidimensional Arrays n Not limited to 2 dimensions n Created same as 1 D arrays, just there are many sizes u Number of rows, cols, flats, etc. 3D6D
130
Copyright 2014 by Janson Industries n Pseudocode n Results in an array with 2 rows and 6 columns n And these are their indices 130 Multidimensional Arrays Declare String eggCartonArray[2] [6] [0] [0] [1][0] [2][0] [3][0] [4][0] [5] [1] [0][1] [1] [2][1] [3][1] [4][1] [5]
131
Copyright 2014 by Janson Industries n If data loaded without specifying the index u Info loaded one line at a time u From left to right n So n Results in… 131 Multidimensional Arrays Declare String eggCartonArray[2] [6] = "a", "b", "c", "d", "e", "f", "g", "h", "i', "j", "k", "l"
132
Copyright 2014 by Janson Industries 132 Multidimensional Arrays abcdef ghijkl Declare String eggCartonArray[2] [6] = "a", "b", "c", "d", "e", "f", "g", "h", "i', "j", "k", "l"
133
Copyright 2014 by Janson Industries n 9 x 3, 2D array holds the par values for a 9 hole golf course n User enters their score for each of the holes, which goes into col 2 n Program calculates u Over/under for each hole (col 3) u Whether it is a birdie, eagle, par, bogie, double bogie, ugh. u Total for the round 133 Multidimensional Arrays
134
Copyright 2014 by Janson Industries 134 Multidimensional Arrays - XD What was your score on hole 1? 3 What was your score on hole 2? 4 What was your score on hole 3? 3 What was your score on hole 4? 7 What was your score on hole 5? 3 What was your score on hole 6? 3 What was your score on hole 7? 5 What was your score on hole 8? 6 What was your score on hole 9? 1 You shot a 35 with 2 eagles, 1 birdie, 3 pars, 2 double bogies, 1 ugh
135
Copyright 2014 by Janson Industries Multidimensional Arrays 135 Module main() Integer courseSize = 9 Integer scoresArray[courseSize] [3] String namesArray[6], msg = " " Integer namesValuesArray[6] [2] scoresArray [0] [0] = 3 scoresArray [1] [0] = 5 scoresArray [2] [0] = 3 scoresArray [3] [0] = 3 scoresArray [4] [0] = 5 scoresArray [5] [0] = 3 scoresArray [6] [0] = 3 scoresArray [7] [0] = 4 scoresArray [8] [0] = 3
136
Copyright 2014 by Janson Industries Multidimensional Arrays 136 namesArray[0] = "eagle" namesArray[1] = "birdie" namesArray[2] = "par" namesArray[3] = "bogie" namesArray[4] = "double bogie" namesArray[5] = "ugh" namesValuesArray[0] [0] = -2 namesValuesArray[1] [0] = -1 namesValuesArray[2] [0] = 0 namesValuesArray[3] [0] = 1 namesValuesArray[4] [0] = 2 namesValuesArray[5] [0] = 3
137
Copyright 2014 by Janson Industries 137 Integer ctr = 1, innerCtr = 0, score, totalScore = 0 //Get scores, calc over/under and totalScore For ctr = 1 to 9 Display "What was your score on hole " + ctr + "? " Input score totalScore = totalScore + score scoresArray [ctr - 1] [1] = score scoresArray [ctr - 1] [2] = score - scoresArray [ctr - 1] [0] //Set ughs and if ugh, don't want to check for other values If (scoresArray [ctr - 1] [2] > 3) Then namesValuesArray[5] [1] = namesValuesArray[5] [1] +1 innerCtr = 7 End If Multidimensional Arrays
138
Copyright 2014 by Janson Industries 138 //Set birdies, bogies, etc. While innerCtr < 6 If (scoresArray [ctr - 1] [2] = namesValuesArray[innerCtr] [0]) Then namesValuesArray[innerCtr] [1] = namesValuesArray[innerCtr] [1] + 1 innerCtr = 7 End If innerCtr = innerCtr + 1 End While End For Multidimensional Arrays
139
Copyright 2014 by Janson Industries 139 //Build birdies, bogies, etc. portion of msg For ctr = 0 to 5 If (namesValuesArray[ctr] [1] > 0) Then msg = msg, namesValuesArray[ctr] [1], " ", namesArray[0] If (namesValuesArray[ctr] [1] > 1) Then msg = msg, "s, " Else msg = msg, ", " End If End For Display "You shot a ", totalScore, " with", msg End Module Multidimensional Arrays
140
Copyright 2014 by Janson Industries import java.util.Scanner; public class GolfScore { static Scanner keyboard = new Scanner(System.in); public static void main(String[] args) { // Variable to hold array sizes int courseSize = 9; // Arrays to hold data int scoresArray[][] = new int[courseSize][3]; String namesArray[] = new String[6]; int namesValuesArray[][] = new int[6][2]; // Various variables int ctr, innerCtr, score, totalScore = 0; String msg = " "; // Initialize arrays // Hole par values scoresArray[0][0] = 3; scoresArray[1][0] = 5; scoresArray[2][0] = 3; scoresArray[3][0] = 3; scoresArray[4][0] = 5; scoresArray[5][0] = 3; scoresArray[6][0] = 3; scoresArray[7][0] = 4; scoresArray[8][0] = 3; 140 Multidimensional Arrays - Java Setting the par values Parallel arrays
141
Copyright 2014 by Janson Industries 141 Multidimensional Arrays - Java namesArray[0] = "eagle"; namesArray[1] = "birdie"; namesArray[2] = "par"; namesArray[3] = "bogie"; namesArray[4] = "double bogie"; namesArray[5] = "ugh"; namesValuesArray[0][0] = -2; namesValuesArray[1][0] = -1; namesValuesArray[2][0] = 0; namesValuesArray[3][0] = 1; namesValuesArray[4][0] = 2; namesValuesArray[5][0] = 3; //Get scores, calc over/under and totalScore for (ctr = 1; ctr <= 9; ctr++) { System.out.print("What was your score on hole " + ctr + "? "); score = keyboard.nextInt(); totalScore = totalScore + score; scoresArray[ctr - 1][1] = score; innerCtr = 0; //Set ughs value if (scoresArray[ctr - 1][2] > 3) { namesValuesArray[5][1] = namesValuesArray[5][1] + 1; innerCtr = 7; } Multidimensional Arrays - Java Parallel arrays values
142
Copyright 2014 by Janson Industries 142 Multidimensional Arrays - Java //Set birdies, bogies, etc. values while (innerCtr < 6) { if (scoresArray[ctr - 1][2] == namesValuesArray[innerCtr][0]) { namesValuesArray[innerCtr][1] = namesValuesArray[innerCtr][1] + 1; innerCtr = 7; } innerCtr = innerCtr + 1; } //Build birdies, bogies, etc. portion of msg for (ctr = 0; ctr < 6; ctr++) { if (namesValuesArray[ctr][1] > 0) { msg = msg + namesValuesArray[ctr][1] + " " + namesArray[ctr]; if (namesValuesArray[ctr][1] > 1) { msg = msg + "s, "; } else { msg = msg + ", "; } // Take off the last comma and space msg = msg.substring(0, msg.length() - 2); System.out.println(" You shot a " + totalScore + " with" + msg); } Multidimensional Arrays - Java Trim off ", "
143
Copyright 2014 by Janson Industries 143 Points to Remember n Arrays contain a series of values u All values must be the same type u Array assigned to a variable u Each value identified by the variable name followed by a subscript (ex. priceArray[2]) n Search an array: u Initialize the subscript to 0 u Use a loop to test each array element value u Stop loop when a match is found
144
Copyright 2014 by Janson Industries 144 Points to Remember n Parallel arrays - multiple arrays where u Each element in one array is associated with the element at the same relative location in another array n Multi-dimensional arrays u Arrays of arrays u Good for holding many sets of related data
145
Copyright 2014 by Janson Industries Assignments n Non-Graded u Chap 8 labs 8.1-8.4 n Graded u Chap 8 lab 8.5 145
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.