ch01a.IntrotoJava

advertisement
Intro to Programming
& Algorithm Design
Arrays
Assg
This presentation can be viewed on line in a file named:
Copyright 2003 by Janson Industriesch08.IntrotoProg.Arrays.ppt
1
Objectives

Explain
 Arrays
 Advantages
 How
of arrays
to process arrays
 Parallel
arrays
 Multi-dimensional

arrays
Show how to implement
arrays in Java
2
Copyright 2014 by Janson Industries
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

Like variables, 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 Industries
4
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 data type first
 Then the name
 Then [max number of values]
 Declare
Integer itemCosts[7]
 Declare String stateAbbrs[4]
Copyright 2014 by Janson Industries
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
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
Copyright 2014 by Janson Industries
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
stateAbbrs[4]
= "GA" results in?
An out of bounds error!
Copyright 2014 by Janson Industries
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,

If not then,


we can deliver to you!
Sorry, we can't deliver to you.
In class assg:
Create
the pseudo code or flow
chart to do this
Copyright 2014 by Janson Industries
11
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
Display "Sorry, we can't deliver to you."
End If
13
End Module
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
18
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
Copyright 2014 by Janson Industries
19
Using
Arrays
Raptor
Copyright 2014 by Janson Industries
20
Using Arrays In Java

Syntax to create similar to
pseudocode

new data type[size]



However, must create an array
variable and assign array to it

data type[] name = new data
type[size]


Copyright 2014 by Janson Industries
new String[3]
new int[3]
String[] zipCodes = new String[3];
int[] qtys = new int[3];
21
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)
Copyright 2014 by Janson Industries
22
Using Arrays In Java
None of the Raptor
Tom Foolery needed
Copyright 2014 by Janson Industries
23
Using Arrays In Java
Copyright 2014 by Janson Industries
24
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
isZipCodeValid = true
End If
End If
End If

Copyright 2014 by Janson Industries
Why use the array?
25
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
isZipCodeValid = true
End If
End For

Copyright 2014 by Janson Industries
But what happens if the delivery
area expands to 6 zip codes? 26
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…
27
Copyright 2014 by Janson Industries
Why Arrays?


…we never have to change the
for statement or size of array
And the for works for any number
of zip codes
Copyright 2014 by Janson Industries
Declare Integer arraySize = 6
Declare String validZipCode[arraySize]
validZipCode[0] = "32246"
validZipCode[1] = "32224"
validZipCode[2] = "32250"
validZipCode[3] = "32252"
Note sentinel
validZipCode[4] = "32244"
value in For
validZipCode[5] = "32228"
For ctr = 0 to (arraySize -1)
If zipCode = validZipCode[ctr] Then
isZipCodeValid = true
End If
28
End For
Using Arrays Efficiently

Using a For loop is inefficient
 Will
always loop the number of
times of the array size


Copyright 2014 by Janson Industries
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
29
Using While to Search
Module main()
Integer arraySize = 6
Integer ctr = 0
StringvalidZipCode[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
30
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
Copyright 2014 by Janson Industries
31
Using Arrays SFC
Copyright 2014 by Janson Industries
32
Using Arrays SFC
Copyright 2014 by Janson Industries
33
Using Arrays Raptor
Copyright 2014 by Janson Industries
34
Using Arrays Raptor
Notice the argument
needed to work in Raptor
Copyright 2014 by Janson Industries
35
Using Arrays Raptor
Copyright 2014 by Janson Industries
36
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? ");
37
Copyright 2014 by Janson Industries
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
38
Using Arrays Java
Copyright 2014 by Janson Industries
39
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
Copyright 2014 by Janson Industries
40
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
41
Arrays
Validate customer
When array
maxed, items
displayed
When "done"
entered, items
displayed
42
Copyright 2014 by Janson Industries
Using Arrays

Better do an internal design and
modularize
main
Validate
Customer
Create
Valid List
Validate
Zip Code
Ask
For Zip
Compare
To List
Copyright 2014 by Janson Industries
Get Order
Items
Display
Order
Read
Items
Display
Items
Display invalid
message
43
Using Arrays

Define method calls
main()
validate
Cust()
Create
Valid List
Validate
Zip Code
Ask
For Zip
Compare
To List
Copyright 2014 by Janson Industries
getOrder()
show
Order()
Read
Items
Display
Items
Display invalid
message
44
Using Method Calls

validateCust() needs to return a
Boolean value to main indicating if the
zip code is valid or not


Because getOrder and showOrder use
orderArray, make orderArray and
orderArraySize static global variables


Copyright 2014 by Janson Industries
If valid, main calls getOrder and showOrder
Global variables are defined within the
class but not in a method
Change name of application to
OrderEntry
45
Partially Filled Arrays

Because the user is entering data,
the array may not have values in
every index location


Three ways to handle:



Copyright 2014 by Janson Industries
Don't want to process empty
locations
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
46
Pseudocode

Main() logic greatly simplified
Declare Integer orderArraySize = 3
Declare String orderArray[orderArraySize]
Module main()
Declare Boolean isCustValid
isCustValid = validateCust()
If(isCustValid) Then
Call getOrder()
Call showOrder()
End If
End Module
Copyright 2014 by Janson Industries
47
Pseudocode

Alternative way to define and
initialize an array
Declare Integer arraySize = 4
Declare String stoogesArray[arraySize] = "Moe",
"Larry", "Curly", "Shemp"
Copyright 2014 by Janson Industries
48
Pseudocode
Function 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
49
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 Function
Copyright 2014 by Janson Industries
50
Pseudocode

Always want to prompt for an item so
a do while is used
Module void getOrder()
Declare Integer ctr = 0
Declare 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
51
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
Copyright 2014 by Janson Industries
52
SFC - OrderEntry
Global
variables
defined
main line
logic
53
Copyright 2014 by Janson Industries
SFC OrderEntry
main line
logic
Copyright 2014 by Janson Industries
54
SFC - OrderEntry
validateCust()
55
Copyright 2014 by Janson Industries
SFC
OrderEntry
validateCust()
56
Copyright 2014 by Janson Industries
SFC - OrderEntry
getOrder()
57
Copyright 2014 by Janson Industries
SFC - OrderEntry
getOrder()
Copyright 2014 by Janson Industries
58
SFC
OrderEntry
showOrder()
59
Copyright 2014 by Janson Industries
Raptor
OrderEntry
main()
Have to initialize
orderArray to nulls ("")
60
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)
61
Copyright 2014 by Janson Industries
Raptor
OrderEntry
validateCustomer()
62
Copyright 2014 by Janson Industries
Raptor
OrderEntry
getOrder()
63
Copyright 2014 by Janson Industries
Raptor
OrderEntry
showOrder()
Check for null value
to see when to stop
64
Copyright 2014 by Janson Industries
Raptor
OrderEntry
When run
65
Copyright 2014 by Janson Industries
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
66
Java OrderEntry

Have the psuedocode and
flowcharts adequately defined
what the application should do?
I
hope you said yes!
import java.util.Scanner;
validateCustomer()
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
67
//
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;
Copyright 2014
} by Janson Industries
68
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++;
Notice use of
}
System.out.println(" ");
equalsIgnoreCase()
} while (ctr < orderArraySize
&& !item.equalsIgnoreCase("Done"));
}
Copyright 2014 by Janson Industries
69
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 method
}
//End of class
}
Copyright 2014 by Janson Industries
Vastly simplified
main()
70
Java OrderEntry
showOrder()
Copyright 2014 by Janson Industries
71
Passing Arrays

Just like strings and numbers,
arrays can be passed and returned
from methods
 Syntax
 To
pretty much the same
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
72
Passing Arrays

Instead of orderArray being a
global variable, have
 getOrder:
 create
orderArray (i.e. making it a local
variable)
 return orderArray to main
 main
Copyright 2014 by Janson Industries
pass orderArray to showOrder
73
Passing Arrays

Must change
 getOrder's
header to indicate it is
returning a String array
 getOrder
needs a return statement to
return the String array orderArray
 showOrder's
headers to accept a
String array
 main
has to:
 creates
an String array variable
 assign orderArray (returned by getOrder)
to it
 passes orderArray to showOrder
Copyright 2014 by Janson Industries

74
Passing Arrays Pseudocode

Main creates String array variable,
assigns the array returned by
getOrder to it, passes it to showOrder
Declare Integer orderArraySize = 3
orderArray not a
global variable
Module main()
Declare String orderArray[orderArraySize]
Declare Boolean isCustValid
isCustValid = validateCust()
If(isCustValid) Then
orderArray = getOrder()
Call showOrder(orderArray)
End If
End Module
Copyright 2014 by Janson Industries
75
No Changes to validateCust
Function 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 Function
Copyright 2014 by Janson Industries
77
Passing Arrays Pseudocode

Change method header to return
array, create and return orderArray
Function 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 Function
Copyright 2014 by Janson Industries
78
Passing Arrays Pseudocode

Change showOrder header to
accept a String array
Module 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 2014 by Janson Industries
79
public class OrderEntryPassArray {
orderArray no longer
a global variable
//Global variables and objects
static int orderArraySize = 3;
private static boolean validateCust(){
:
:
:
Same code as before
:
A String array
will be returned
orderArray is a
local variable
:
Passing
Arrays
Java
:
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
:
:
:
orderArray
is returned
return orderArray;
//End of method
}
Copyright 2012 by Janson Industries
80
private static void showOrder(String[] orderArray) { showOrder accepts
int ctr = 0;
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
Still works correctly
82
Copyright 2012 by Janson Industries
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
Copyright 2014 by Janson Industries
84
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 = testScoresArray[ctr]
End If
ctr = ctr + 1
End While
Copyright 2014 by Janson Industries
86
Processing An Array

Finding the sum
Declare Integer sumValue, ctr = 0
While (ctr < testScoresArraySize AND
testScoresArray[ctr] <> "")
sumValue = sumValue + testScoresArray[ctr]
ctr = ctr + 1
End While
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, avgValue, ctr = 0
While (ctr < testScoresArraySize AND
testScoresArray[ctr] <> "")
sumValue = sumValue + testScoresArray[ctr]
ctr = ctr + 1
End While
avgValue = sumValue/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()
Copyright 2014 by Janson Industries
90
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
Set ctr to the 2nd
test score because…
Loop from 2 until ctr = 6
Calc the sum
Copyright 2014 by Janson Industries
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
For instance storing employee
information like
 Name
 Address
 Phone
Copyright 2014 by Janson Industries
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 2 Oak 3 Elm
St.
St.
St.

Phone array
1111111
Copyright 2014 by Janson Industries
2222222
3333333
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
 Change
total number of items
message to display
 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
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
Copyright 2014 by Janson Industries
way to return 2 array variables
101
Parallel Arrays

getOrder will
 Display
the new text
 Populate
both arrays with values
 Calculate
and return the total
number of items


Copyright 2014 by Janson Industries
main will get the total and pass
to showOrder
showOrder will receive the total
and display the new text
102
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
Notice "s" on items with qty >1
5 Large calzones
103
Copyright 2014 by Janson Industries
Passing Arrays Pseudocode
Declare Integer orderArraySize = 3
Declare String orderArray[orderArraySize]
Declare String qtyArray[orderArraySize]
orderArray &
Module main()
qtyArray are
Declare Boolean isCustValid
global parallel
Integer total
arrays
isCustValid = validateCust()
If(isCustValid) Then
New variable
total = getOrder()
total passed
Call showOrder(total)
End If
End Module
Copyright 2014 by Janson Industries
104
No Changes to validateCust
Function 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 Function
Copyright 2014 by Janson Industries
106
Passing Arrays Pseudocode

New variables to hold qty info
Function String[] getOrder()
Integer ctr = 0, totalQty, qty
String item
Do
Display "Enter what would you like or Done"
Input item
Setting parallel
If item <> "Done" Then
arrays' values
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 < orderArraySize AND item <> "Done")
Return totalQty
107
Copyright
2014
by
Janson
Industries
End Function
Passing Arrays Pseudocode
Module showOrder(Integer totalQty)
Integer ctr = 0
Display “The following are the “, totalQty,
“ items you have ordered”
While (ctr < orderArraySize AND
Displaying item
and qty info
orderArray[ctr] <> "")
Display qtyArray[ctr], " ", orderArray[ctr]
If (qtyArray[ctr] > 1)
Make item plural
Display “s”
End If
Skip to next line
ctr = ctr + 1
End While
End Module
108
Copyright 2014 by Janson Industries
Passing Arrays Raptor
Just declared
some new
variables
No changes to
validateCustomer
Copyright 2014 by Janson Industries
109
Passing Arrays Raptor
Declare the new
qty variables
Initialize totalQty
Copyright 2014 by Janson Industries
110
Get qty info,
load into array
Calc totalQty
Copyright 2014 by Janson Industries
111
New msg variable
needed to pluralize item
Passing
Arrays
Raptor
Display total items
Build msg with qty and item
Make msg plural
Copyright 2014 by Janson Industries
112
public class ParallelArrays {
New qtyArray and
//Global variables and objects
global variable
static int orderArraySize = 3;
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 = "";
New qty and
String qty = "";
totalQty variables
int totalQty = 0;
//Variables and objects needed to read from command line
:
:
:
If item not
if (!item.equalsIgnoreCase("Done")) {
"done", get qty
orderArray[ctr] = item;
System.out.print("How many " + item +"s would you like ");
try {
Load qtyArray and
qty = keyboard.nextLine();
accumulate totalQty
qtyArray[ctr] = qty;
totalQty = totalQty + Integer.parseInt(qty);
} catch (IOException e) {
e.printStackTrace();
}
ctr++;
}
113
:
:
:
Return totalQty
return
Copyright
2014totalQty;
by Janson Industries
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
main has a
totalQty variable
Gets totalQty
and passes
private static void showOrder(int totalQty){
showOrder
int ctr = 0;
accepts totalQty
//Displays order items
System.out.println("The following are the " + totalQty + " items
you have ordered");
New message
while (ctr < orderArraySize
114
with totalQty
&& !(orderArray[ctr] == null)){
System.out.print(qtyArray[ctr] + " ");
System.out.print(orderArray[ctr]);
Prints qty and item
if (Integer.parseInt(qtyArray[ctr]) > 1) {
System.out.println("s");}
If more than
else {System.out.println(" ");}
one, adds an "s"
ctr++;
}
//End of method
} 2014 by Janson Industries
Copyright
Prompts for
items & amounts
Copyright 2014 by Janson Industries
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
Copyright 2014 by Janson Industries
entered, A returned
116
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
117
Copyright 2014 by Janson Industries
Parallel Arrays


Will create two parallel arrays to
hold the grades and limits
gradeArray
F

C
B
A
69.5
79.5
89.5
100.5
rangeArray
64.5
Copyright 2014 by Janson Industries
D
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
Module main()
Integer arraySize = 5
String gradeArray[arraySize]
Real rangeArray[arraySize]
Copyright 2014 by Janson Industries
gradeArray[0]
gradeArray[1]
gradeArray[2]
gradeArray[3]
gradeArray[4]
=
=
=
=
=
"F"
"D"
"C"
"B"
"A"
rangeArray[0]
rangeArray[1]
rangeArray[2]
rangeArray[3]
rangeArray[4]
=
=
=
=
=
64.5
69.5
79.5
89.5
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
Copyright 2014 by Janson Industries
121
Finding
a Range
Raptor
Initialize the
arrays
Copyright 2014 by Janson Industries
122
Initialize the
other variables
Finding
a Range
Raptor
Notice how loop
condition changed
Copyright 2014 by Janson Industries
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
gradeArray[0]
gradeArray[1]
gradeArray[2]
gradeArray[3]
gradeArray[4]
the array with letter grades
= "F";
= "D";
= "C";
= "B";
= "A";
// Initialize
rangeArray[0]
rangeArray[1]
rangeArray[2]
rangeArray[3]
rangeArray[4]
the array with grade range upper limit
= 64.5;
= 69.5;
= 79.5;
= 89.5;
= 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 {
If range found, no need
126
ctr++;
}
to increase loop counter
}
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
}
Copyright 2010 by Janson Industries
127
Copyright 2010 by Janson Industries
Multidimensional Arrays


Arrays don't have to consist of a
single row
A multi-row index is a two
dimensional array. Examples:
A
Copyright 2014 by Janson Industries
spreadsheet table
 An
egg carton
 Pill
box
128
Multidimensional Arrays

Not limited to 2 dimensions
3D
6D

Created same as 1 D arrays,
just there are many sizes
 Number
Copyright 2014 by Janson Industries
of rows, cols, flats, etc
129
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]
[1] [0] [1] [1] [1] [2] [1] [3] [1] [4] [1] [5]
Copyright 2014 by Janson Industries
130
Multidimensional Arrays

If data loaded without specifying
the index
 Info
loaded one line/row 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"

Copyright 2014 by Janson Industries
Results in…
131
Multidimensional Arrays
Declare String eggCartonArray[2] [6]
= "a", "b", "c", "d", "e", "f", "g",
"h", "i', "j", "k", "l"
a
b
c
d
e
f
g
h
i
j
k
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 calcs
 Over/under
for each hole (col 3)
 Whether
it is a birdie, eagle, par,
bogie, double bogie, or ugh.
 Total
Copyright 2014 by Janson Industries
for the round
133
Multidimensional Arrays - XD
What
What
What
What
What
What
What
What
What
was
was
was
was
was
was
was
was
was
your
your
your
your
your
your
your
your
your
score
score
score
score
score
score
score
score
score
on
on
on
on
on
on
on
on
on
hole
hole
hole
hole
hole
hole
hole
hole
hole
1?
2?
3?
4?
5?
6?
7?
8?
9?
3
4
3
7
3
3
5
6
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
scoresArray
scoresArray
scoresArray
scoresArray
scoresArray
scoresArray
scoresArray
scoresArray
Copyright 2014 by Janson Industries
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[0]
[0]
[0]
[0]
[0]
[0]
[0]
[0]
[0]
=
=
=
=
=
=
=
=
=
3
5
3
3
5
3
3
4
3
135
scoresArray
Par
Hole Over/
Score Under
3
5
3
3
5
3
3
4
3
Copyright 2014 by Janson Industries
136
Multidimensional Arrays
namesArray[0]
namesArray[1]
namesArray[2]
namesArray[3]
namesArray[4]
namesArray[5]
=
=
=
=
=
=
"eagle"
"birdie"
"par"
"bogie"
"double bogie"
"ugh"
namesValuesArray[0]
namesValuesArray[1]
namesValuesArray[2]
namesValuesArray[3]
namesValuesArray[4]
namesValuesArray[5]
Copyright 2014 by Janson Industries
[0]
[0]
[0]
[0]
[0]
[0]
=
=
=
=
=
=
-2
-1
0
1
2
3
137
namesArray
eagle birdie
par
bogie double ugh
bogie
namesValuesArray
# of each
Copyright 2014 by Janson Industries
eagle
-2
birdie
-1
par
0
bogie
double
bogie
ugh
1
2
3
138
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] =
namesValuesArray[5] [1] +1
innerCtr = 7
End If
Copyright 2014 by Janson Industries
139
scoresArray
Par
What
What
What
What
What
What
What
What
What
was
was
was
was
was
was
was
was
was
your
your
your
your
your
your
your
your
your
score
score
score
score
score
score
score
score
score
Copyright 2014 by Janson Industries
on
on
on
on
on
on
on
on
on
hole
hole
hole
hole
hole
hole
hole
hole
hole
1?
2?
3?
4?
5?
6?
7?
8?
9?
3
4
3
7
3
3
5
6
1
Hole Over/
Score Under
3
3
0
5
4
-1
3
3
0
3
7
4
5
3
-2
3
3
0
3
5
2
4
6
2
3
1
-2
140
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
Copyright 2014 by Janson Industries
141
namesValuesArray
# of each
eagle
-2
2
birdie
-1
1
par
0
3
bogie
1
0
2
2
3
1
double bogie
ugh
Copyright 2014 by Janson Industries
142
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[ctr]
If (namesValuesArray[ctr] [1] > 1) Then
msg = msg, "s, "
Else
msg = msg, ", "
End If
End If
End For
Display "You shot a ", totalScore, " with", msg
End Module
Copyright 2014 by Janson Industries
143
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];
Parallel
int namesValuesArray[][] = new int[6][2];
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;
scoresArray[8][0]
= 3;
Copyright 2014
by Janson Industries
Multidimensional
Arrays - Java
Setting the par values
144
namesArray[0]
namesArray[1]
namesArray[2]
namesArray[3]
namesArray[4]
namesArray[5]
=
=
=
=
=
=
"eagle";
"birdie";
"par";
"bogie";
"double bogie";
"ugh";
Multidimensional
Multidimensional
Arrays - Java
Arrays - Java
namesValuesArray[0][0]
namesValuesArray[1][0]
namesValuesArray[2][0]
namesValuesArray[3][0]
namesValuesArray[4][0]
namesValuesArray[5][0]
=
=
=
=
=
=
-2;
-1;
0;
1;
2;
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
145
//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;
}
Multidimensional Arrays - Java
}
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
Trim off ", "
msg = msg.substring(0, msg.length() - 2);
System.out.println(" You shot a " + totalScore + " with" + msg);
}
}
Copyright 2014 by Janson Industries
146
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/index (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
147
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 of the same type
Copyright 2014 by Janson Industries
148
Assignments

Non-Graded
Chap

8 labs 8.1-8.4
Graded
Chap
8 lab 8.5
149
Copyright 2014 by Janson Industries
Download