1 intro to programming & algorithm design arrays copyright 2003 by janson industries this...
TRANSCRIPT
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
Copyright 2014 by Janson Industries2
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 Industries3
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
Copyright 2014 by Janson Industries4
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
Variable Multiple user or file input values
• Shopping cart items
Copyright 2014 by Janson Industries5
Array When creating, specify
The type of values it will hold The maximum number of values it will hold A name
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]
Copyright 2014 by Janson Industries6
Array Can use a variable to define size
Instead of a fixed constant
Especially useful for multiple arrays holding related data Lists of items for sale, descriptions, and prices
If number of items for sale changes, just change arraySize and all arrays changed
Declare Integer arraySize = 4Declare String stateAbbrs[arraySize]
Copyright 2014 by Janson Industries7
Array String stateAbbrs[4] results in
To refer to a particular value, use the variable name and index number in brackets stateAbbrs[2] = "FL" results inIndex 0 1 2 3
Index 0 1 2 3
FL
Copyright 2014 by Janson Industries8
Array Let's be clear:
stateAbbrs[2] = "FL" results in data be put into the third position of the array
stateAbbrs[4] = "GA" results in?Index 0 1 2 3
FL
An out of bounds error!
Copyright 2014 by Janson Industries
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
As mentioned, can assign data in program or read data from keyboard/file and assign to array
9
Copyright 2014 by Janson Industries
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
Will ask user for zip code, read it, and read array to confirm it is valid
10
Copyright 2014 by Janson Industries
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
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
A little harder than you thought?
This initializes the array, displays the prompt and reads the zip
Copyright 2014 by Janson Industries
Using Arrays
13
Boolean isZipCodeValid = falseFor ctr = 0 to 2
If zipCode = validZipCode[ctr] Then isZipCodeValid = true
End If End ForIf isZipCodeValid = true Then
Display "Great, we can deliver to you!"Else
Display "Sorry, we can't deliver to you."End If
End Module
Need to keep track if zip is valid or not: isZipCodeValid
Copyright 2014 by Janson Industries14
Using Arrays - SFC
Copyright 2014 by Janson Industries
Using Arrays - SFC
15
Copyright 2014 by Janson Industries
Using Arrays in Raptor
16
A Raptor array index starts at 1 String stateAbbrs[4] results in
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 rightIndex 1 2 3 4
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
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
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
Copyright 2014 by Janson Industries
Using Arrays Raptor
20
Copyright 2014 by Janson Industries
Using Arrays In Java
21
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];
Copyright 2014 by Janson Industries
Lets look at this closer:
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
Copyright 2014 by Janson Industries
Using Arrays In Java
23
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];
Copyright 2014 by Janson Industries
Using Arrays In Java
24
None of the Raptor Tom Foolery needed
Copyright 2014 by Janson Industries
Using Arrays In Java
25
Copyright 2014 by Janson Industries26
Why Arrays? Could have done the same
thing with this
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 End If End If
Copyright 2014 by Janson Industries27
Why Arrays? There really wasn't a lot less
code using the array
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
Copyright 2014 by Janson Industries28
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
And if instead of hard coding the array size, we had created a variable to hold the size…
Copyright 2014 by Janson Industries29
Why Arrays? …we never have to change the
for statement or size of array And the for works for any number
of zip codesDeclare Integer arraySize = 6Declare 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
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
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
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 ThenDisplay "Great, we can deliver to
you!"Else
Display "Sorry, we can't deliver to you."
End Module
Copyright 2014 by Janson Industries
Using Arrays SFC
33
Copyright 2014 by Janson Industries
Using Arrays SFC
34
Copyright 2014 by Janson Industries
Using Arrays Raptor
35
Copyright 2014 by Janson Industries
Using Arrays Raptor
36
Notice the argument needed to work in
Raptor
Copyright 2014 by Janson Industries
Using Arrays Raptor
37
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 codesvalidZipCode[0] = "32246";validZipCode[1] = "32224";validZipCode[2] = "32250";
validZipCode[3] = "32252"; validZipCode[4] = "32244"; validZipCode[5] = "32228";
// Prints out a blank line and promptSystem.out.println(" ");System.out.print("What is your zip code? "); 38
Using Arrays Java
Copyright 2014 by Janson Industries
// Read the zipzipCode = 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 notSystem.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
Copyright 2014 by Janson Industries
Using Arrays Java
40
Copyright 2014 by Janson Industries
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
Need New array to hold info Loop to load array Loop to display array contents
41
Copyright 2014 by Janson Industries
Using Arrays 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? 33333Sorry, 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 pizzaDiet soda
Copyright 2014 by Janson Industries43
Validate customer
When array maxed, items
displayed
When "done" entered, items
displayed
Arrays
Copyright 2014 by Janson Industries
DisplayItems
Compare To List
Using Arrays Better do an internal design and
modularize
44
main
ValidateCustomer
Get OrderItems
DisplayOrder
ValidateZip Code
Display invalid message
ReadItems
Create Valid List
AskFor Zip
Copyright 2014 by Janson Industries
DisplayItems
Compare To List
Using Arrays Define method calls
45
main()
validateCust()
getOrder() showOrder()
ValidateZip Code
Display invalid message
ReadItems
Create Valid List
AskFor Zip
Copyright 2014 by Janson Industries
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
Using Method Calls
46
Copyright 2014 by Janson Industries
Because the user is entering data, the array may not have values in every index location Don't want to process empty
locations
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
Partially Filled Arrays
47
Copyright 2014 by Janson Industries
Pseudocode
48
Main() logic greatly simplified
Declare Integer orderArraySize = 3Declare String orderArray[orderArraySize]
Module main()Declare Boolean isCustValidisCustValid = validateCust()If(isCustValid) Then
getOrder()showOrder()
End IfEnd Module
Copyright 2014 by Janson Industries
Pseudocode
49
Alternative way to define and initialize an array
Declare Integer arraySize = 4Declare String stoogesArray[arraySize] = "Moe",
"Larry", "Curly", "Shemp"
Copyright 2014 by Janson Industries
Pseudocode
50
Module Boolean validateCust()Integer ctr = 0Boolean isZipCodeValid = false
Integer zipCodeArraySize = 6String validZipCode[zipCodeArraySize] =
"32246", "32224", "32250", "32252", "32244", "32228"
String zipCode
Display "What is your zip code?" Input zipCode
Copyright 2014 by Janson Industries
Pseudocode
51
While (ctr < zipCodeArraySize AND isZipCodeValid = false)
If zipCode = validZipCode[ctr] Then isZipCodeValid = true
End Ifctr = ctr + 1
End While
If isZipCodeValid = false ThenDisplay "Sorry, we can't deliver to
you."End If
return isZipCodeValidEnd Module
Copyright 2014 by Janson Industries
Pseudocode
52
Module void getOrder() Integer ctr = 0
String itemDo
Display "Enter what would you like or Done"
Input itemIf item <> "Done" Then orderArray[ctr] = item ctr = ctr + 1End If
While (ctr < orderArraySize AND item <> "Done")End Module
Always want to prompt for an item so a do while is used
Copyright 2014 by Janson Industries
Pseudocode
53
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
Copyright 2014 by Janson Industries54
SFC - OrderEntry
Global variables defined
main line logic
Copyright 2014 by Janson Industries 55
SFC OrderEntry
main line logic
Copyright 2014 by Janson Industries56
validateCust()
SFC - OrderEntry
Copyright 2014 by Janson Industries57
validateCust()
SFCOrderEntry
Copyright 2014 by Janson Industries58
getOrder()
SFC - OrderEntry
Copyright 2014 by Janson Industries 59
getOrder()
SFC - OrderEntry
Copyright 2014 by Janson Industries60
showOrder()
SFCOrderEntry
Copyright 2014 by Janson Industries61
RaptorOrderEntry
main()
Have to initialize orderArray to nulls ("")
Copyright 2014 by Janson Industries62
validateCustomer()
RaptorOrderEntry
All the old zip code validation code is here
(don't forget Raptor arrays start at 1 not 0)
Copyright 2014 by Janson Industries63
RaptorOrderEntryvalidateCustomer()
Copyright 2014 by Janson Industries64
getOrder()
RaptorOrderEntry
Copyright 2014 by Janson Industries65
showOrder()
RaptorOrderEntry
Check for null value to see when to stop
Copyright 2014 by Janson Industries66
When run
RaptorOrderEntry
Copyright 2014 by Janson Industries 67
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
Java
String stoogesArray[] = {"Moe", "Larry", "Curley", "Shemp"};
Copyright 2014 by Janson Industries 68
Have the pseudocode and flowcharts adequately defined what the application should do? 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 statusString zipCode ="";Boolean isZipCodeValid = false;
Java OrderEntry
validateCustomer()
Copyright 2014 by Janson Industries 69
// Variables and objects needed to hold valid zip codesint zipCodeArraySize = 6;
// Create and initialize the array with valid zip codesString[] validZipCode = {"32246", "32224", "32250",
"32252", "32244", "32228"} ;
// Prints out a blank line and user promptSystem.out.println(" ");System.out.print("What is your zip code? ");
// Read the zipzipCode = keyboard.nextLine();
// Check the array to validate the entered zip codeint ctr = 0;while (ctr < zipCodeArraySize && isZipCodeValid == false) { if (zipCode.equals(validZipCode[ctr])) {
isZipCodeValid = true; }
ctr++; }
// Possibly displays invalid messageif (isZipCodeValid == false) {
System.out.print("Sorry, we can't deliver to you.") }
System.out.println(" ");
// Returns whether zip was valid or notreturn isZipCodeValid;
}
Copyright 2014 by Janson Industries 70
// Prompts user for order items and stores in orderArrayprivate static void getOrder(){
// Variables and objects needed to store order itemsString 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 OrderEntrygetOrder()
Notice use of equalsIgnoreCase()
Copyright 2014 by Janson Industries 71
// Displays ordered itemsprivate 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 OrderEntryshowOrder()
Copyright 2014 by Janson Industries 72
showOrder()
Java OrderEntry
Copyright 2014 by Janson Industries 73
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 74
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
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 IfEnd Module
orderArray not a global variable
Main creates variable, assigns the array returned by getOrder to it, passes it to showOrder
Copyright 2014 by Janson Industries
No Changes to validateCust
76
Module Boolean validateCust()Integer ctr = 0Boolean isZipCodeValid = false
Integer zipCodeArraySize = 6String validZipCode[zipCodeArraySize] =
"32246", "32224", "32250", "32252", "32244", "32228"
String zipCode
Display "What is your zip code?" Input zipCode
Copyright 2014 by Janson Industries
No Changes to validateCust
77
While (ctr < zipCodeArraySize AND isZipCodeValid = false)
if zipCode = validZipCode[ctr] then isZipCodeValid = true
End Ifctr = ctr + 1
End While
if isZipCodeValid = false thenDisplay "Sorry, we can't deliver to
you."End If
return isZipCodeValidEnd Module
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 itemIf item <> "Done" Then orderArray[ctr] = item ctr = ctr + 1End If
While (ctr < orderArraySize AND item <> "Done")Return orderArray
End Module
Change method header to return array, create and return orderArray
Copyright 2014 by Janson Industries
Passing Arrays Pseudocode
79
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
Copyright 2012 by Janson Industries 80
private static String[] getOrder(){
//Variables and objects needed to store order itemsString 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 objectsstatic 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
Copyright 2012 by Janson Industries 81
private static void showOrder(String[] orderArray) {int ctr = 0;
// Displays order itemsSystem.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 ordersBoolean isCustValid = false;String[] orderArray;
isCustValid = OrderEntryPassArray.validateCust();if (isCustValid){
//If valid invokes getOrder and receives orderArrayorderArray = OrderEntryPassArray.getOrder();
//Invokes showOrder and passes orderArray to the methodOrderEntryPassArray.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
Copyright 2012 by Janson Industries82
Still works correctly
Copyright 2014 by Janson Industries 83
Processing An Array How can you find the following
for the values in an array Largest
Smallest
Total
Average
Copyright 2014 by Janson Industries 84
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
Copyright 2014 by Janson Industries 85
Processing An Array
Declare Integer largestValue, ctr = 1largestValue = testScoresArray[0]While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") If testScoresArray[ctr] > largestValue Then
largestValue = testScoresArray[ctr] End If
ctr = ctr + 1End While
Finding the largest value
Copyright 2014 by Janson Industries 86
Processing An Array
Declare Integer smallestValue, ctr = 1smallestValue = testScoresArray[0]While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") If testScoresArray[ctr] < smallestValue Then
smallestValue = testScoresArray[ctr] End If
ctr = ctr + 1End While
Finding the smallest value Very similar to largest search
Copyright 2014 by Janson Industries
Finding the sum
87
Processing An Array
Declare Integer sumValue, ctr = 0While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") sumValue = sumValue + testScoresArray[ctr] ctr = ctr + 1End While
Copyright 2014 by Janson Industries
Finding the average Have to find the sum then divide by the number of values
Which we have kept track of with ctr
88
Processing An Array
Declare Integer sumValue, avgValue, ctr = 0While (ctr < testScoresArraySize AND testScoresArray[ctr] <> "") sumValue = sumValue + testScoresArray[ctr] ctr = ctr + 1End WhileavgValue = sumValue/ctr
Copyright 2014 by Janson Industries
Will have main() perform all the calculations
Will have two other methods initializeScoreTestArray()
Loads the scores
displayValues() shows the scores and calculated values
89
Processing An Array - Raptor
Copyright 2014 by Janson Industries 90
Processing An Array - RaptorinitializeTestScoreArray()
Copyright 2014 by Janson Industries 91
Processing An Array - RaptordisplayValues()
Loop to show individual scores
Copyright 2014 by Janson Industries 92
Processing An Array - RaptordisplayValues()
Puts out a blank line then the four calculated values
Copyright 2014 by Janson Industries 93
Processing An Array - Raptormain()
Initialize the scoresSet 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
Copyright 2014 by Janson Industries 94
Processing An Array - Raptormain()
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 95
Processing An Array - Raptor
Results
Copyright 2014 by Janson Industries 96
Parallel Arrays Use more than one array to store
many pieces of related information
Related info stored in same relative position in each array
For instance storing employee information like Name Address Phone number
Copyright 2014 by Janson Industries 97
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 98
Parallel Arrays Done with the following 3 arrays
Name array
Address array
Phone array
Joe
1 MainSt.
111-1111
Mary
2 OakSt.
222-2222
333-3333
3 ElmSt.
Pam
Copyright 2014 by Janson Industries 99
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
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)
Copyright 2014 by Janson Industries 100
Parallel Arrays So when an item is entered
It's qty is entered in the same position in the qtyArray
pizza
6
Copyright 2014 by Janson Industries 101
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
Copyright 2014 by Janson Industries 102
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
Copyright 2014 by Janson Industries
Parallel Arrays Here’s the external design of
changes to application
103
What is your zip code? 33333Sorry, we can't deliver to you.
What is your zip code? 32228
Enter what would you like or Done Pepperoni pizzaHow many Pepperoni pizzas would you like 6
Enter what would you like or Done Small diet colaHow many Small diet colas would you like 1
Enter what would you like or Done Large calzoneHow many Large calzones would you like 5
The following are the 12 items you have ordered:6 Pepperoni pizzas1 Small diet cola5 Large calzones
Notice "s" on items with qty >1
Copyright 2014 by Janson Industries
Passing Arrays Pseudocode
104
Declare Integer orderArraySize = 3Declare String orderArray[orderArraySize]Declare String qtyArray[orderArraySize]
Module main() Declare Boolean isCustValid Integer total isCustValid = validateCust() If(isCustValid) Then
total = getOrder()showOrder(total)
End IfEnd Module
orderArray & qtyArray are
global parallel arrays
New variable total passed
Copyright 2014 by Janson Industries
No Changes to validateCust
105
Module Boolean validateCust()Integer ctr = 0Boolean isZipCodeValid = false
Integer zipCodeArraySize = 6String validZipCode[zipCodeArraySize] =
"32246", "32224", "32250", "32252", "32244", "32228"
String zipCode
Display "What is your zip code?" Input zipCode
Copyright 2014 by Janson Industries
No Changes to validateCust
106
While (ctr < zipCodeArraySize AND isZipCodeValid = false)
if zipCode = validZipCode[ctr] then isZipCodeValid = true
End Ifctr = ctr + 1
End While
if isZipCodeValid = false thenDisplay "Sorry, we can't deliver to
you."End If
return isZipCodeValidEnd Module
Copyright 2014 by Janson Industries
Passing Arrays Pseudocode
107
Module String[] getOrder() Integer ctr = 0, totalQty
String item, qtyDo
Display "Enter what would you like or Done"Input itemIf item <> "Done" Then orderArray[ctr] = item
Display “How many “, item, “s would you like“
Input qtyqtyArray[ctr] = qtytotalQty = totalQty + qty
ctr = ctr + 1End If
While (ctr < orderArraySize AND item <> "Done")Return totalQty
End Module
New variables to hold qty info
Setting parallel
arrays' values
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
Copyright 2014 by Janson Industries
Passing Arrays Raptor
109
Just declared some new variables
No changes to validateCustom
er
Copyright 2014 by Janson Industries
Passing Arrays Raptor
110
Declare the new qty variables
Initialize totalQty
Copyright 2014 by Janson Industries111
Get qty info, load into array
Calc totalQty
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
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
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 totalQtyPrints qty and
itemIf more than one, adds an
"s"
Copyright 2014 by Janson Industries115
Notice the total
and individual amounts
Prompts for items & amounts
Copyright 2014 by Janson Industries116
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
Copyright 2014 by Janson Industries117
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
Parallel Arrays Will create two parallel arrays to
hold the grades and limits
gradeArray
rangeArray
ABC
100.589.579.5
DF
64.5 69.5
Copyright 2014 by Janson Industries119
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.
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.5rangeArray[1] = 69.5rangeArray[2] = 79.5rangeArray[3] = 89.5rangeArray[4] = 100.5
Copyright 2014 by Janson Industries121
Integer ctr = 0Integer numericGrade = 0Boolean 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 IfEnd WhileDisplay " "Display "A numeric grade of ", numericGrade,
" is equal to a letter grade of ", gradeArray[ctr]);End Module
Finding a Range
Copyright 2014 by Janson Industries
Finding a Range Raptor
122
Initialize the arrays
Copyright 2014 by Janson Industries
Finding a Range Raptor
123
Notice how loop condition changed
Initialize the other variables
Copyright 2014 by Janson Industries
Finding a Range - Raptor
124
Copyright 2010 by Janson Industries
125
import java.util.Scanner;
public class LetterGrade {// Variables and objects needed to read from command linestatic Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {// Variable to hold array sizesint arraySize = 5;
// Arrays to hold grade and rangesString[] gradeArray = new String[arraySize];double[] rangeArray = new double[arraySize];
// Initialize the array with letter gradesgradeArray[0] = "F";gradeArray[1] = "D";gradeArray[2] = "C";gradeArray[3] = "B";gradeArray[4] = "A";
// Initialize the array with grade range upper limitrangeArray[0] = 64.5;rangeArray[1] = 69.5;rangeArray[2] = 79.5;rangeArray[3] = 89.5;rangeArray[4] = 100.5;
Java Range Search
Copyright 2010 by Janson Industries
126
// Loop control variablesint ctr = 0;Boolean isGradeAssigned = false;
// Variable to hold input valuesdouble numericGradeDouble = 0;
// Prints out a blank line and instructionSystem.out.println(" ");System.out.print("What is the numeric grade? ");
// Read the numeric gradenumericGradeDouble = keyboard.nextDouble();
// Search the array to find the correct rangewhile (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
Copyright 2010 by Janson Industries127
Copyright 2014 by Janson Industries 128
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
Copyright 2014 by Janson Industries 129
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
Copyright 2014 by Janson Industries
Pseudocode
Results in an array with 2 rows and 6 columns
And these are their indices
130
Multidimensional Arrays
Declare String eggCartonArray[2] [6]
[0] [0] [0] [1] [0] [2] [0] [3] [0] [4] [0] [5]
[1] [0] [1] [1] [1] [2] [1] [3] [1] [4] [1] [5]
Copyright 2014 by Janson Industries
If data loaded without specifying the index Info loaded one line at a time
From left to right
So
Results in…
131
Multidimensional Arrays
Declare String eggCartonArray[2] [6] = "a", "b", "c", "d", "e", "f", "g", "h", "i', "j", "k", "l"
Copyright 2014 by Janson Industries
132
Multidimensional Arrays
a b c d e f
g h i j k l
Declare String eggCartonArray[2] [6] = "a", "b", "c", "d", "e", "f", "g", "h", "i', "j", "k", "l"
Copyright 2014 by Janson Industries
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
Multidimensional Arrays
Copyright 2014 by Janson Industries 134
Multidimensional Arrays - XDWhat was your score on hole 1? 3What was your score on hole 2? 4What was your score on hole 3? 3What was your score on hole 4? 7What was your score on hole 5? 3What was your score on hole 6? 3What was your score on hole 7? 5What was your score on hole 8? 6What 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
Multidimensional Arrays
135
Module main()Integer courseSize = 9
Integer scoresArray[courseSize] [3]String namesArray[6], msg = " "Integer namesValuesArray[6] [2]
scoresArray [0] [0] = 3scoresArray [1] [0] = 5scoresArray [2] [0] = 3scoresArray [3] [0] = 3scoresArray [4] [0] = 5scoresArray [5] [0] = 3scoresArray [6] [0] = 3scoresArray [7] [0] = 4scoresArray [8] [0] = 3
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] = -2namesValuesArray[1] [0] = -1namesValuesArray[2] [0] = 0namesValuesArray[3] [0] = 1namesValuesArray[4] [0] = 2namesValuesArray[5] [0] = 3
Copyright 2014 by Janson Industries137
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
Copyright 2014 by Janson Industries138
//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 + 1End While
End For
Multidimensional Arrays
Copyright 2014 by Janson Industries139
//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 IfEnd If
End For
Display "You shot a ", totalScore, " with", msgEnd Module
Multidimensional Arrays
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 sizesint courseSize = 9;
// Arrays to hold dataint scoresArray[][] = new int[courseSize][3];String namesArray[] = new String[6];int namesValuesArray[][] = new int[6][2];
// Various variablesint ctr, innerCtr, score, totalScore = 0;String msg = " ";
// Initialize arrays// Hole par valuesscoresArray[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
Copyright 2014 by Janson Industries141
Multidimensional Arrays - JavanamesArray[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 totalScorefor (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
Copyright 2014 by Janson Industries142
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 msgfor (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 spacemsg = msg.substring(0, msg.length() - 2);System.out.println(" You shot a " + totalScore + " with" + msg);}
}
Multidimensional Arrays - Java
Trim off ", "
Copyright 2014 by Janson Industries143
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 Industries144
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
Good for holding many sets of related data
Copyright 2014 by Janson Industries
Assignments Non-Graded
Chap 8 labs 8.1-8.4
Graded
Chap 8 lab 8.5
145