Intro to the AS/400

Download Report

Transcript Intro to the AS/400

Intro to Programming & Algorithm Design

Arrays

Assg

This presentation can be viewed on line in a file named: Copyright 2003 by Janson Industries

ch08.IntrotoProg.Arrays.ppt

1

Objectives

 Explain  Arrays  Advantages of arrays  How to process arrays  Parallel arrays  Multi-dimensional arrays  Show how to implement arrays in Java Copyright 2014 by Janson Industries 2

Array

 A programming

data structure

that holds multiple values  Think of it as a single row of data  Array values  Must all be of the same type  An array of strings, or an array of integers, or an array of…  Can't have an array that has both strings and integers and…  Individual values are referred to by an index (or subscript)  The index begins at 0 3 Copyright 2014 by Janson Industries

Array

 Arrays are fixed in length  Arrays have a size - the max number of values they can hold  An array is assigned a name  Array values can be:  Constant  Fixed values for program use • Discount rates, zip codes Copyright 2014 by Janson Industries  Variable  Multiple user or file input values • Shopping cart items 4

Array

 When creating, specify  The type of values it will hold  The maximum number of values it will hold  A name Copyright 2014 by Janson Industries  To indicate this in pseudocode and flowcharts  Specify the value type first  Then the name  [

maximum number of values

]  Declare Integer itemCosts [ 7 ]  Declare String stateAbbrs [ 4 ] 5

Array

 Can use a variable to define size  Instead of a fixed constant Declare Integer arraySize = 4 Declare String stateAbbrs[arraySize ]  Especially useful for multiple arrays holding related data  Lists of items for sale, descriptions, and prices  Copyright 2014 by Janson Industries If number of items for sale changes, just change arraySize and all arrays changed 6

Array

 String stateAbbrs[4] results in Index 0 1 2 3 Copyright 2014 by Janson Industries  To refer to a particular value, use the variable name and index number in brackets  stateAbbrs[2] = "FL" results in Index 0 1 2 3 FL 7

Array

 Let's be clear:  stateAbbrs[2] = "FL" results in data be put into the third position of the array Index 0 1 2 3 FL Copyright 2014 by Janson Industries  stateAbbrs[4] = "GA" results in?

An out of bounds error!

8

Array Advantages

 Great for storing lists of data  Instead of defining many variables to hold data use one array  Easy to process array data in a loop  Another good reason to use a size variable Copyright 2014 by Janson Industries  As mentioned, can assign data in program or read data from keyboard/file and assign to array 9

Using Arrays

 A pizza parlor application will accept orders for delivery  Only deliver to certain zip codes  Will build an array with valid zip codes of  32246  32224  32250 Copyright 2014 by Janson Industries  Will ask user for zip code, read it, and read array to confirm it is valid 10

Using Arrays

 If the zip code is valid, display the text  Great, we can deliver to you!

 If not then,  Sorry, we can't deliver to you.

 In class assg:  Create the pseudo code or flow chart to do this 11 Copyright 2014 by Janson Industries

Using Arrays

 A little harder than you thought?

 This initializes the array, displays the prompt and reads the zip Module main() Declare String zipCode, validZipCode[3] validZipCode[0] = "32246" validZipCode[1] = "32224" validZipCode[2] = "32250" Display "What is your zip code?" Input zipCode Copyright 2014 by Janson Industries 12

Using Arrays

 Need to keep track if zip is valid or not: isZipCodeValid  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 End If End Module Copyright 2014 by Janson Industries Display "Sorry, we can't deliver to you." 13

Using Arrays - SFC

Copyright 2014 by Janson Industries 14

Using Arrays - SFC

Copyright 2014 by Janson Industries 15

Using Arrays in Raptor

 A Raptor array index starts at 1  String stateAbbrs[4] results in Index 1 2 3 4  Also, if you enter a zip code (32246) Raptor assumes it is a number  Must engage in some "tom foolery" to get it to work right Copyright 2014 by Janson Industries 16

Using Arrays Raptor

When zipCode read we concatenate an "s" to make it a String and assign to stringZipCode

Copyright 2014 by Janson Industries 17

Using Arrays Raptor

In the validity check, we concatenate an "s" to the value in the array and compare to stringZipCode

18 Copyright 2014 by Janson Industries

Using Arrays Raptor

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

19 Copyright 2014 by Janson Industries

Copyright 2014 by Janson Industries

Using Arrays Raptor

20

Using Arrays In Java

 Syntax to create similar to pseudocode  new

type

[

size

]  new String [ 3 ]  new int [ 3 ]  However, must create an array variable and assign array to it 

type

[]

name

= new

type

[

size

]   String [] zipCodes = new String [ 3 ]; int [] qtys = new int [ 3 ]; 21 Copyright 2014 by Janson Industries

Using Arrays In Java

 Lets look at this closer:  String [] zipCodes = new String [ 3 ] ; 2

Creates a Sting array variable named zipCodes

3 1

Creates a String array of size 3 Assigns the String array to zipCodes (the String array variable)

22 Copyright 2014 by Janson Industries

Using Arrays In Java

 Syntax to create similar to pseudocode  new

type

[

size

];  new String [ 3 ] ;  new int [ 3 ] ;  However, must create an array variable and assign array to it 

type

[]

name

= new

type

[

size

];   String [] zipCodes = new String [ 3 ]; int [] qtys = new int [ 3 ]; 23 Copyright 2014 by Janson Industries

Copyright 2014 by Janson Industries

Using Arrays In Java

None of the Raptor Tom Foolery needed

24

Using Arrays In Java

Copyright 2014 by Janson Industries 25

Why Arrays?

 Could have done the same thing with this If zipCode ="32246" Then isZipCodeValid = true Else If zipCode ="32224" Then isZipCodeValid = true Else If zipCode ="32250" Then End If isZipCodeValid = true End If End If Copyright 2014 by Janson Industries  Why use the array?

26

Why Arrays?

 There really wasn't a lot less code using the array Declare String validZipCode[3] validZipCode[0] = "32246" validZipCode[1] = "32224" validZipCode[2] = "32250" For ctr = 0 to 2 If zipCode = validZipCode[ctr] Then End For isZipCodeValid = true End If Copyright 2014 by Janson Industries  But what happens if the delivery area expands to 6 zip codes? 27

Why Arrays?

 The if logic keeps expanding  With the array:  Change the size of the array  Add an initialization statement for each new value  Change the for statement sentinel value Copyright 2014 by Janson Industries  And if instead of hard coding the array size, we had created a variable to hold the size… 28

Why Arrays?

 …we never have to change the for statement or size of array  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) End For isZipCodeValid = true End If Note sentinel value in For If zipCode = validZipCode[ctr] Then 29 Copyright 2014 by Janson Industries

Using Arrays Efficiently

 Using a For loop is inefficient  Will always loop the number of times of the array size  We want to stop looping as soon as we find a match  So we'll change the loop to a while with a compound condition 30 Copyright 2014 by Janson Industries

Using While to Search

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 31 Copyright 2014 by Janson Industries

Using Arrays

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 32 Copyright 2014 by Janson Industries

Using Arrays SFC

Copyright 2014 by Janson Industries 33

Using Arrays SFC

Copyright 2014 by Janson Industries 34

Using Arrays Raptor

Copyright 2014 by Janson Industries 35

Using Arrays Raptor

Notice the argument needed to work in Raptor

Copyright 2014 by Janson Industries 36

Using Arrays Raptor

Copyright 2014 by Janson Industries 37

import java.util.Scanner;

Using Arrays Java

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? "); Copyright 2014 by Janson Industries 38

// //

Using Arrays Java

Read the zip zipCode = keyboard.nextLine(); Check the array while (ctr < arraySize && isZipCodeValid == false) { if (zipCode.equals(validZipCode[ctr])) { isZipCodeValid = true; } } ctr = ctr + 1;

Notice the argument needed to work in Java

// // // } 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 Copyright 2014 by Janson Industries 39

Using Arrays Java

Copyright 2014 by Janson Industries 40

Using Arrays

 The app is so popular, customer now wants it to accept orders  So if zip code is valid  Accept up to 3 order items  Store in array  Display all items at end Copyright 2014 by Janson Industries  Need  New array to hold info  Loop to load array  Loop to display array contents 41

Using Arrays

 Better do an external design (XD) of new app so we can be sure of what the user wants 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 Copyright 2014 by Janson Industries 42

Arrays

Copyright 2014 by Janson Industries

Validate customer When array maxed, items displayed When "done" entered, items displayed

43

Using Arrays

 Better do an internal design and modularize main Validate Customer Create Valid List Validate Zip Code Get Order Items Read Items Display Order Display Items Ask For Zip Compare To List Copyright 2014 by Janson Industries Display invalid message 44

Using Arrays

 Define method calls main() validate Cust() Create Valid List Validate Zip Code getOrder() Read Items show Order() Display Items Ask For Zip Compare To List Copyright 2014 by Janson Industries Display invalid message 45

Using Method Calls

 validateCust() needs to return a Boolean value to main indicating if the zip code is valid or not  If valid, main calls getOrder and showOrder  Because getOrder and showOrder use orderArray, make orderArray and orderArraySize static global variables  Global variables are defined within the class but not in a method  Change name of application to OrderEntry Copyright 2014 by Janson Industries 46

Partially Filled Arrays

 Because the user is entering data, the array may not have values in every index location  Don't want to process empty locations  Copyright 2014 by Janson Industries Two ways to handle:    Check for an empty value Keep track of how many values are entered Put a sentinel value in the location after the last valid value 47

Pseudocode

 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 Copyright 2014 by Janson Industries 48

Pseudocode

 Alternative way to define and initialize an array Declare Integer arraySize = 4 Declare String stoogesArray[arraySize] = "Moe", "Larry", "Curly", "Shemp" 49 Copyright 2014 by Janson Industries

Pseudocode

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 Copyright 2014 by Janson Industries 50

Pseudocode

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 51 Copyright 2014 by Janson Industries

Pseudocode

 Always want to prompt for an item so a do while is used 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 < orderArraySize AND item <> "Done") End Module 52 Copyright 2014 by Janson Industries

Pseudocode

 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 53 Copyright 2014 by Janson Industries

SFC - OrderEntry

Global variables defined main line logic 54 Copyright 2014 by Janson Industries

Copyright 2014 by Janson Industries

SFC OrderEntry

main line logic 55

SFC - OrderEntry

validateCust() 56 Copyright 2014 by Janson Industries

Copyright 2014 by Janson Industries

SFC OrderEntry

validateCust() 57

SFC - OrderEntry

getOrder() Copyright 2014 by Janson Industries 58

SFC - OrderEntry

Copyright 2014 by Janson Industries getOrder() 59

Copyright 2014 by Janson Industries

SFC OrderEntry

showOrder() 60

Copyright 2014 by Janson Industries

Raptor OrderEntry

main() Have to initialize orderArray to nulls ("") 61

Copyright 2014 by Janson Industries

Raptor OrderEntry

validateCustomer() All the old zip code validation code is here (don't forget Raptor arrays start at 1 not 0) 62

Copyright 2014 by Janson Industries

Raptor OrderEntry

validateCustomer() 63

Copyright 2014 by Janson Industries

Raptor OrderEntry

getOrder() 64

Copyright 2014 by Janson Industries

Raptor OrderEntry

showOrder() Check for null value to see when to stop 65

Copyright 2014 by Janson Industries

Raptor OrderEntry

When run 66

Java

 Alternative way to define and initialize an array  Don't specify a size for the array  Instead of explicitly creating an array object, supply values  Surrounded with {}  Separated by commas String stoogesArray[] = {"Moe", "Larry", "Curley", "Shemp"}; Copyright 2014 by Janson Industries 67

Java OrderEntry

 Have the pseudocode and flowcharts adequately defined what the application should do?

 I hope you said yes!

validateCustomer() 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; Copyright 2014 by Janson Industries 68

// 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; 69

Java OrderEntry

getOrder() // 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 Notice use of equalsIgnoreCase() && !item.equalsIgnoreCase("Done")); } 70 Copyright 2014 by Janson Industries

Java OrderEntry

// Displays ordered items private static void showOrder(){ 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 class } End of method } Copyright 2014 by Janson Industries Vastly simplified main() 71

Java OrderEntry

Copyright 2014 by Janson Industries showOrder() 72

Passing Arrays

 Just like strings and numbers, arrays can be passed and returned from methods  Syntax pretty much the same  To pass a string array 

methodName

(

arrayVariableName

)  To return a string array  in header: String[]

methodName

 at method end: return

arrayVariableName

 Arrays make passing many or a variable number of values easier Copyright 2014 by Janson Industries 73

Passing Arrays

 Instead of making orderArray a global variable, have  getOrder create orderArray & return it  showOrder will have orderArray passed to it  Must change  Both methods headers  getOrder needs a return statement  main creates an array variable, assigns orderArray (returned by getOrder) to it, passes it to showOrder 74 Copyright 2014 by Janson Industries

Passing Arrays Pseudocode

 Main creates variable, assigns the array returned by getOrder to it, passes it to showOrder 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

75 Copyright 2014 by Janson Industries

No Changes to validateCust

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 Copyright 2014 by Janson Industries 76

No Changes to validateCust

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 77 Copyright 2014 by Janson Industries

Passing Arrays Pseudocode

 Change method header to return array, create and return orderArray 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 < orderArraySize AND item <> "Done") Return orderArray End Module Copyright 2014 by Janson Industries 78

Passing Arrays Pseudocode

 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 79 Copyright 2014 by Janson Industries

public class OrderEntryPassArray { //Global variables and objects static int orderArraySize = 3;

orderArray no longer a global variable private static boolean validateCust(){

: : :

Same code as before

: : :

Passing Arrays Java

A String array will be returned

private static String[] getOrder(){

orderArray is a local variable

//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

: : :

orderArray is returned return orderArray;

//End of method 80

private static void showOrder(String[] orderArray) { int ctr = 0;

showOrder accepts a String array

// 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; main has a local String array variable

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 }

main gets the order array and passes it to showOrder

Copyright 2012 by Janson Industries 81

Copyright 2012 by Janson Industries

Still works correctly

82

Processing An Array

 How can you find the following for the values in an array  Largest  Smallest  Total  Average Copyright 2014 by Janson Industries 83

Processing An Array

 Say you have an array of test scores  Create a variable to hold the largest value  Read the first value and set it as the largest  Then loop through the remaining values and compare each to the largest  If new value larger, set largest value to it 84 Copyright 2014 by Janson Industries

Processing An Array

 Finding the largest value 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 Copyright 2014 by Janson Industries 85

Processing An Array

 Finding the smallest value  Very similar to largest search Declare Integer smallestValue , ctr = 1 smallestValue = testScoresArray[0] While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") If testScoresArray[ctr] < smallestValue Then smallestValue End If ctr = ctr + 1 End While = testScoresArray[ctr] 86 Copyright 2014 by Janson Industries

Processing An Array

 Finding the sum Declare Integer ctr = ctr + 1 End While sumValue , ctr = testScoresArray[ctr] <> "") 0 While (ctr < testScoresArraySize AND sumValue = sumValue + testScoresArray[ctr] Copyright 2014 by Janson Industries 87

Processing An Array

 Finding the average  Have to find the sum then divide by the number of values  Which we have kept track of with ctr Declare Integer sumValue, ctr = ctr + 1 End While avgValue = sumValue/ctr avgValue testScoresArray[ctr] <> "") , ctr = 0 While (ctr < testScoresArraySize AND sumValue = sumValue + testScoresArray[ctr] Copyright 2014 by Janson Industries 88

Processing An Array - Raptor

 Will have main() perform all the calculations  Will have two other methods  initializeScoreTestArray()  Loads the scores  displayValues()  shows the scores and calculated values Copyright 2014 by Janson Industries 89

Processing An Array - Raptor

initializeTestScoreArray() 90 Copyright 2014 by Janson Industries

Processing An Array - Raptor

displayValues() Loop to show individual scores Copyright 2014 by Janson Industries 91

Processing An Array - Raptor

displayValues() Puts out a blank line then the four calculated values Copyright 2014 by Janson Industries 92

Processing An Array - Raptor

main() Initialize the scores … we capture the first test score with these variables Loop from 2 until ctr = 6 Copyright 2014 by Janson Industries Set ctr to the 2nd test score because… Calc the sum 93

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) Copyright 2014 by Janson Industries 94

Processing An Array - Raptor

Results Copyright 2014 by Janson Industries 95

Parallel Arrays

 Use more than one array to store many pieces of related information  Related info stored in same relative position in each array Copyright 2014 by Janson Industries  For instance storing employee information like  Name  Address  Phone number 96

Parallel Arrays

 For 3 employees with the following info:  Joe lives at 1 Main St. and has a phone number of 111-1111  Mary lives at 2 Oak St. and has a phone number of 222-2222  Pam lives at 1 Elm St. and has a phone number of 333-3333 Copyright 2014 by Janson Industries 97

Parallel Arrays

 Done with the following 3 arrays  Name array Joe Mary Pam  Address array 1 Main St.

2 Oak St.

3 Elm St.

 Phone array 111 1111 222 2222 Copyright 2014 by Janson Industries 333 3333 98

Parallel Arrays

 Change OrderEntry to accept a quantity for each item  User will enter a qty for each order item  Qty will be saved in qtyArray  Accumulate total number of items Copyright 2014 by Janson Industries  Change message to say  The following are the XX items you have ordered  Have the qty before each item  If qty > 1, add an "s" to item (make item plural) 99

Parallel Arrays

 So when an item is entered pizza  It's qty is entered in the same position in the qtyArray 6 Copyright 2014 by Janson Industries 100

Parallel Arrays

 Because getOrder creates two arrays must make the array variables global  Why?

 Java methods can only return a single variable  No way to return 2 array variables 101 Copyright 2014 by Janson Industries

Parallel Arrays

 getOrder will  Display the new text  Populate both arrays with values  Calculate and return the total number of items  main will get the total and pass to showOrder  showOrder will receive the total and display the new text 102 Copyright 2014 by Janson Industries

Parallel Arrays

 Here’s the external design of changes to application 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 103 Copyright 2014 by Janson Industries

Passing Arrays Pseudocode

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

104 Copyright 2014 by Janson Industries

No Changes to validateCust

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 Copyright 2014 by Janson Industries 105

No Changes to validateCust

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 106 Copyright 2014 by Janson Industries

Passing Arrays Pseudocode

 New variables to hold qty info 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 Input qty qtyArray[ctr] = qty totalQty = totalQty + qty ctr = ctr + 1

Setting parallel arrays' values

Display “How many “, item, “s would you like“ End If While (ctr < orderArraySize AND item <> "Done") Return totalQty End Module 107

Passing Arrays Pseudocode

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

Make item plural Displaying item and qty info

108 Copyright 2014 by Janson Industries

Passing Arrays Raptor

Just declared some new variables No changes to validateCustomer

109 Copyright 2014 by Janson Industries

Passing Arrays Raptor

Declare the new qty variables Initialize totalQty

110 Copyright 2014 by Janson Industries

Copyright 2014 by Janson Industries

Get qty info, load into array Calc totalQty

111

Copyright 2014 by Janson Industries

New msg variable needed to pluralize item

Passing Arrays Raptor

Display total items Build msg with qty and item Make msg plural

112

public class ParallelArrays { //Global variables and objects static int orderArraySize = 3;

New qtyArray and global variable

static String[] orderArray = new String[orderArraySize];

static String[] qtyArray = new String[orderArraySize];

: : : private static int getOrder(){ //Variables and objects needed to store order items String item = "";

String qty = ""; int totalQty = 0; } catch (IOException e) { e.printStackTrace(); }

ctr++;

New qty and totalQty variables

//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 "); Get qty only if not done try { qty = dataIn.readLine(); qtyArray[ctr] = qty; Load qtyArray and accumulate totalQty totalQty = totalQty + Integer.parseInt(qty);

} 113 : : :

Return totalQty

public static void main(String[] args) { // Variable to hold customer status Boolean isCustValid = false;

int totalQty = 0; main has a totalQty variable

isCustValid = ParallelArrays.validateCust(); if (isCustValid){ } // End of method

totalQty = ParallelArrays.getOrder(); ParallelArrays.showOrder(totalQty); Gets totalQty and passes

private static void showOrder(int totalQty){ int ctr = 0; //Displays order items

showOrder accepts totalQty System.out.println("The following are the " + totalQty + " items you have ordered");

while (ctr < orderArraySize && !(orderArray[ctr] == null)){

New message with totalQty System.out.print(qtyArray[ctr] + " ");

System.out.print(orderArray[ctr]);

Prints qty and item if (Integer.parseInt(qtyArray[ctr]) > 1) { System.out.println("s");}

else {System.out.println(" ");} ctr++;

If more than one, adds an "s"

} //End of method }

Copyright 2014 by Janson Industries

Prompts for items & amounts Notice the total and individual amounts

115

Parallel Arrays - Finding a Range

 Store the upper or lower limit of each range in the array  Compare value to limit  If < or > (depending on whether upper of lower limit) you have found the correct range  Example assigning a letter grade to a numeric grade  99 entered, A returned 116 Copyright 2014 by Janson Industries

Finding a Range

 Our ranges for the letter grades will be  F < 64.5

 D < 69.5

 C < 79.5

 B < 89.5

 A < 100.5

Copyright 2014 by Janson Industries 117

Parallel Arrays

 Will create two parallel arrays to hold the grades and limits  gradeArray F D C B A  rangeArray 64.5

69.5

79.5

89.5

100.5

Copyright 2014 by Janson Industries

Finding a Range

 When user enters a numeric grade will compare it to the first value in the rangeArray[]  If entered grade less than 64.5 we have found the correct position in the array  Display the letter grade in the same location of the gradeArray  Else compare to next location in rangeArray, etc.

119 Copyright 2014 by Janson Industries

Finding a Range

Copyright 2014 by Janson Industries 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

120

Integer ctr = 0 Integer numericGrade = 0 Boolean isGradeAssigned = false Display " " Display "What is the numeric grade? " Input numericGrade

Finding a Range

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 121 Copyright 2014 by Janson Industries

Copyright 2014 by Janson Industries

Finding a Range Raptor

Initialize the arrays

122

Initialize the other variables

Copyright 2014 by Janson Industries

Finding a Range Raptor

Notice how loop condition changed

123

Finding a Range - Raptor

Copyright 2014 by Janson Industries 124

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;

Java Range Search

// 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; Copyright 2010 by Janson Industries 125

// 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(" "); 126

If range found, no need to increase loop counter

System.out.print("A numeric grade of " + numericGradeString + " is equal to a letter grade of " + gradeArray[ctr]); // End of method } // End of class } Copyright 2010 by Janson Industries

Copyright 2010 by Janson Industries 127

Multidimensional Arrays

 Arrays don't have to consist of a single row  A multi-row index is a two dimensional array. Examples:  A spreadsheet table  An egg carton  Pill box 128 Copyright 2014 by Janson Industries

Multidimensional Arrays

 Not limited to 2 dimensions  Created same as 1 D arrays, just there are many sizes  Number of rows, cols, flats, etc.

3D 6D 129 Copyright 2014 by Janson Industries

Multidimensional Arrays

 Pseudocode Declare String eggCartonArray[2] [6]  Results in an array with 2 rows and 6 columns  And these are their indices [0] [0] [0] [1] [0] [2] [0] [3] [0] [4] [0] [5] Copyright 2014 by Janson Industries [1] [0] [1] [1] [1] [2] [1] [3] [1] [4] [1] [5] 130

Multidimensional Arrays

 If data loaded without specifying the index  Info loaded one line at a time  From left to right  So Declare String eggCartonArray[2] [6] = "a", "b", "c", "d", "e", "f", "g", "h", "i', "j", "k", "l"  Results in… 131 Copyright 2014 by Janson Industries

Multidimensional Arrays

Declare String eggCartonArray[2] [6] = "a", "b", "c", "d", "e", "f", "g", "h", "i', "j", "k", "l" a g b h c i d j e k f l 132 Copyright 2014 by Janson Industries

Multidimensional Arrays

 9 x 3, 2D array holds the par values for a 9 hole golf course  User enters their score for each of the holes, which goes into col 2  Program calculates  Over/under for each hole (col 3)  Whether it is a birdie, eagle, par, bogie, double bogie, ugh.

 Total for the round 133 Copyright 2014 by Janson Industries

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 Copyright 2014 by Janson Industries 134

Multidimensional Arrays

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 135 Copyright 2014 by Janson Industries

Multidimensional Arrays

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 Copyright 2014 by Janson Industries 136

Multidimensional Arrays

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] = End If namesValuesArray[5] [1] +1 innerCtr = 7 137 Copyright 2014 by Janson Industries

Multidimensional Arrays

//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 138 Copyright 2014 by Janson Industries

Multidimensional Arrays

//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 End If msg = msg, ", " End If End For Display "You shot a ", totalScore, " with", msg End Module 139 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];

Parallel arrays

// 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;

Multidimensional Arrays - Java

Setting the par values

140

namesArray[0] = "eagle"; namesArray[3] = "bogie"; namesArray[4] = "double bogie"; namesArray[5] = "ugh";

Multidimensional Arrays - Java

namesValuesArray[0][0] = -2; namesValuesArray[1][0] = -1; namesValuesArray[2][0] = 0; namesValuesArray[3][0] = 1; namesValuesArray[4][0] = 2; namesValuesArray[5][0] = 3;

Parallel arrays values

//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; } Copyright 2014 by Janson Industries 141

} //Set birdies, bogies, etc. values

Multidimensional Arrays - Java

namesValuesArray[innerCtr][1] = } } namesValuesArray[innerCtr][1] + 1; innerCtr = 7; innerCtr = innerCtr + 1;

Multidimensional Arrays - Java

//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);

Trim off ", "

System.out.println(" You shot a " + totalScore + " with" + msg); } } Copyright 2014 by Janson Industries 142

Points to Remember

 Arrays contain a series of values  All values must be the same type  Array assigned to a variable  Each value identified by the variable name followed by a subscript (ex. priceArray[2])  Search an array:  Initialize the subscript to 0  Use a loop to test each array element value  Stop loop when a match is found Copyright 2014 by Janson Industries 143

Points to Remember

 Parallel arrays - multiple arrays where  Each element in one array is associated with the element at the same relative location in another array  Multi-dimensional arrays  Arrays of arrays Copyright 2014 by Janson Industries  Good for holding many sets of related data 144

Assignments

 Non-Graded  Chap 8 labs 8.1-8.4

 Graded  Chap 8 lab 8.5

Copyright 2014 by Janson Industries 145