lesson 5
TRANSCRIPT
![Page 1: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/1.jpg)
Computer Skills and Programming Update
Lesson 5
![Page 2: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/2.jpg)
2
Outline
Enumerated Types
The while Statement
do while Statement
The for Statement
Declaring and Using Arrays
![Page 3: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/3.jpg)
3
Enumerated Types• Java allows you to define an enumerated type,
which can then be used to declare variables
• An enumerated type declaration lists all possible values for a variable of that type
• The values are identifiers of your own choosing
• The following declaration creates an enumerated type called Seasonenum Season {winter, spring, summer, fall};
• Any number of values can be listed
![Page 4: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/4.jpg)
4
Enumerated Types• Once a type is defined, a variable of that
type can be declared:Season time;
• And it can be assigned a value:
time = Season.fall;
• The values are referenced through the name of the type
• Enumerated types are type-safe – you cannot assign any value other than those listed
![Page 5: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/5.jpg)
5
Ordinal Values• Internally, each value of an enumerated type
is stored as an integer, called its ordinal value
• The first value in an enumerated type has an ordinal value of zero, the second one, and so on
• However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value
![Page 6: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/6.jpg)
6
Enumerated Types• The declaration of an enumerated type is a
special type of class, and each variable of that type is an object
• The ordinal method returns the ordinal value of the object
• The name method returns the name of the identifier corresponding to the object's value
• See IceCream.java
![Page 7: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/7.jpg)
7
//********************************************************************// IceCream.java Author: Lewis/Loftus//// Demonstrates the use of enumerated types.//********************************************************************
public class IceCream{ enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee, rockyRoad, mintChocolateChip, cookieDough}
//----------------------------------------------------------------- // Creates and uses variables of the Flavor type. //----------------------------------------------------------------- public static void main (String[] args) { Flavor cone1, cone2, cone3;
cone1 = Flavor.rockyRoad; cone2 = Flavor.chocolate;
System.out.println ("cone1 value: " + cone1); System.out.println ("cone1 ordinal: " + cone1.ordinal()); System.out.println ("cone1 name: " + cone1.name());
continued
![Page 8: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/8.jpg)
8
continued
System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name());
cone3 = cone1;
System.out.println (); System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); }}
![Page 9: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/9.jpg)
9
continued
System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name());
cone3 = cone1;
System.out.println (); System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); }}
Outputcone1 value: rockyRoadcone1 ordinal: 5cone1 name: rockyRoadcone2 value: chocolatecone2 ordinal: 1cone2 name: chocolatecone3 value: rockyRoadcone3 ordinal: 5cone3 name: rockyRoad
![Page 10: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/10.jpg)
10
Outline
Enumerated Types
The while Statement
do while Statement
The for Statement
Declaring and Using Arrays
![Page 11: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/11.jpg)
11
Repetition Statements• Repetition statements allow us to execute a
statement multiple times
• Often they are referred to as loops
• Like conditional statements, they are controlled by boolean expressions
• Java has three kinds of repetition statements: while, do, and for loops
![Page 12: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/12.jpg)
12
The while Statement• A while statement has the following syntax:
while ( condition ) statement;
• If the condition is true, the statement is executed
• Then the condition is evaluated again, and if it is still true, the statement is executed again
• The statement is executed repeatedly until the condition becomes false
![Page 13: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/13.jpg)
13
Logic of a while Loop
statement
truefalse
conditionevaluated
![Page 14: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/14.jpg)
14
The while Statement• An example of a while statement:
• If the condition of a while loop is false initially, the statement is never executed
• Therefore, the body of a while loop will execute zero or more times
int count = 1;while (count <= 5){ System.out.println (count); count++;}
![Page 15: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/15.jpg)
15
Sentinel Values• Let's look at some examples of loop processing
• A loop can be used to maintain a running sum
• A sentinel value is a special input value that represents the end of input
• See Average.java
![Page 16: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/16.jpg)
16
//********************************************************************// Average.java Author: Lewis/Loftus//// Demonstrates the use of a while loop, a sentinel value, and a// running sum.//********************************************************************
import java.text.DecimalFormat;import java.util.Scanner;
public class Average{ //----------------------------------------------------------------- // Computes the average of a set of values entered by the user. // The running sum is printed as the numbers are entered. //----------------------------------------------------------------- public static void main (String[] args) { int sum = 0, value, count = 0; double average;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt();
continue
![Page 17: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/17.jpg)
17
continue
while (value != 0) // sentinel value of 0 to terminate loop { count++;
sum += value; System.out.println ("The sum so far is " + sum);
System.out.print ("Enter an integer (0 to quit): "); value = scan.nextInt(); }
continue
![Page 18: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/18.jpg)
18
continue
System.out.println ();
if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); } }}
![Page 19: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/19.jpg)
19
continue
System.out.println ();
if (count == 0) System.out.println ("No values were entered."); else { average = (double)sum / count;
DecimalFormat fmt = new DecimalFormat ("0.###"); System.out.println ("The average is " + fmt.format(average)); } }}
Sample RunEnter an integer (0 to quit): 25The sum so far is 25Enter an integer (0 to quit): 164The sum so far is 189Enter an integer (0 to quit): -14The sum so far is 175Enter an integer (0 to quit): 84The sum so far is 259Enter an integer (0 to quit): 12The sum so far is 271Enter an integer (0 to quit): -35The sum so far is 236Enter an integer (0 to quit): 0
The average is 39.333
![Page 20: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/20.jpg)
20
Input Validation• A loop can also be used for input validation,
making a program more robust
• It's generally a good idea to verify that input is valid (in whatever sense) when possible
• See WinPercentage.java
![Page 21: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/21.jpg)
21
//********************************************************************// WinPercentage.java Author: Lewis/Loftus//// Demonstrates the use of a while loop for input validation.//********************************************************************
import java.text.NumberFormat;import java.util.Scanner;
public class WinPercentage{ //----------------------------------------------------------------- // Computes the percentage of games won by a team. //----------------------------------------------------------------- public static void main (String[] args) { final int NUM_GAMES = 12; int won; double ratio;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of games won (0 to " + NUM_GAMES + "): "); won = scan.nextInt();
continue
![Page 22: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/22.jpg)
22
continue
while (won < 0 || won > NUM_GAMES) { System.out.print ("Invalid input. Please reenter: "); won = scan.nextInt(); }
ratio = (double)won / NUM_GAMES;
NumberFormat fmt = NumberFormat.getPercentInstance();
System.out.println (); System.out.println ("Winning percentage: " + fmt.format(ratio)); }}
![Page 23: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/23.jpg)
23
continue
while (won < 0 || won > NUM_GAMES) { System.out.print ("Invalid input. Please reenter: "); won = scan.nextInt(); }
ratio = (double)won / NUM_GAMES;
NumberFormat fmt = NumberFormat.getPercentInstance();
System.out.println (); System.out.println ("Winning percentage: " + fmt.format(ratio)); }}
Sample RunEnter the number of games won (0 to 12): -5Invalid input. Please reenter: 13Invalid input. Please reenter: 7
Winning percentage: 58%
![Page 24: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/24.jpg)
24
Infinite Loops• The body of a while loop eventually must
make the condition false
• If not, it is called an infinite loop, which will execute until the user interrupts the program
• This is a common logical error
• You should always double check the logic of a program to ensure that your loops will terminate normally
![Page 25: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/25.jpg)
25
Infinite Loops• An example of an infinite loop:
• This loop will continue executing until interrupted (Control-C) or until an underflow error occurs
int count = 1;while (count <= 25){ System.out.println (count); count = count - 1;}
![Page 26: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/26.jpg)
26
Nested Loops• Similar to nested if statements, loops can
be nested as well
• That is, the body of a loop can contain another loop
• For each iteration of the outer loop, the inner loop iterates completely
![Page 27: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/27.jpg)
27
Quick CheckHow many times will the string "Here" be printed?
count1 = 1;while (count1 <= 3){ count2 = 1; while (count2 < 5) { System.out.println ("Here"); count2++; } count1++;}
![Page 28: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/28.jpg)
28
Quick CheckHow many times will the string "Here" be printed?
count1 = 1;while (count1 <= 3){ count2 = 1; while (count2 < 5) { System.out.println ("Here"); count2++; } count1++;}
3* 4 = 12
![Page 29: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/29.jpg)
29
Outline
Enumerated Types
The while Statement
do while Statement
The for Statement
Declaring and Using Arrays
![Page 30: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/30.jpg)
30
Logic of a do while Loop
true
conditionevaluated
statement
false
![Page 31: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/31.jpg)
31
The do Statement• An example of a do loop:
• The body of a do loop executes at least once
• See ReverseNumber.java
int count = 0;do{ count++; System.out.println (count);} while (count < 5);
![Page 32: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/32.jpg)
32
Comparing while and do
statement
true false
conditionevaluated
The while Loop
true
conditionevaluated
statement
false
The do Loop
![Page 33: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/33.jpg)
33
Outline
Enumerated Types
The while Statement
do while Statement
The for Statement
Declaring and Using Arrays
![Page 34: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/34.jpg)
34
The for Statement• A for statement has the following syntax:
for ( initialization ; condition ; increment ) statement;
The initializationis executed once
before the loop begins
The statement isexecuted until the
condition becomes false
The increment portion is executed at the end of each
iteration
![Page 35: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/35.jpg)
35
Logic of a for loop
statement
true
conditionevaluated
false
increment
initialization
![Page 36: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/36.jpg)
36
The for Statement• A for loop is functionally equivalent to the
following while loop structure:
initialization;while ( condition ){ statement; increment;}
![Page 37: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/37.jpg)
37
The for Statement• An example of a for loop:
for (int count=1; count <= 5; count++) System.out.println (count);
• The initialization section can be used to declare a variable
• Like a while loop, the condition of a for loop is tested prior to executing the loop body
• Therefore, the body of a for loop will execute zero or more times
![Page 38: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/38.jpg)
38
The for Statement• An example of a for loop:
for (int count=1; count <= 5; count++) System.out.println (count);
The while equivalent would be:
int count = 1;while (count <= 5){ System.out.println (count); count++;}
![Page 39: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/39.jpg)
39
The for Statement• The increment section can perform any
calculation:
for (int num=100; num > 0; num -= 5) System.out.println (num);
• A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance
• See Multiples.java
![Page 40: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/40.jpg)
40
//********************************************************************// Multiples.java Author: Lewis/Loftus//// Demonstrates the use of a for loop.//********************************************************************
import java.util.Scanner;
public class Multiples{ //----------------------------------------------------------------- // Prints multiples of a user-specified number up to a user- // specified limit. //----------------------------------------------------------------- public static void main (String[] args) { final int PER_LINE = 5; int value, limit, mult, count = 0;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter a positive value: "); value = scan.nextInt();
continue
![Page 41: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/41.jpg)
41
continue
System.out.print ("Enter an upper limit: "); limit = scan.nextInt();
System.out.println (); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:");
for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t");
// Print a specific number of values per line of output count++; if (count % PER_LINE == 0) System.out.println(); } }}
![Page 42: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/42.jpg)
42
continue
System.out.print ("Enter an upper limit: "); limit = scan.nextInt();
System.out.println (); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:");
for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t");
// Print a specific number of values per line of output count++; if (count % PER_LINE == 0) System.out.println(); } }}
Sample RunEnter a positive value: 7Enter an upper limit: 400
The multiples of 7 between 7 and 400 (inclusive) are:7 14 21 28 3542 49 56 63 7077 84 91 98 105112 119 126 133 140147 154 161 168 175182 189 196 203 210217 224 231 238 245252 259 266 273 280287 294 301 308 315322 329 336 343 350357 364 371 378 385392 399
![Page 43: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/43.jpg)
43
Quick CheckWrite a code fragment that counts and prints on the screen, the total number of even numbers between 1 and 100.
int count = 0;
for (int num=1; num <= 100; num++)
if (num%2 == 0)
count++;
Sytem.out.println (count);
![Page 44: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/44.jpg)
44
The for Statement• Each expression in the header of a for loop is
optional
• If the initialization is left out, no initialization is performed
• If the condition is left out, it is always considered to be true, and therefore creates an infinite loop
• If the increment is left out, no increment operation is performed
![Page 45: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/45.jpg)
45
//********************************************************************// Stars.java Author: Lewis/Loftus//// Demonstrates the use of nested for loops.//********************************************************************
public class Stars{ //----------------------------------------------------------------- // Prints a triangle shape using asterisk (star) characters. //----------------------------------------------------------------- public static void main (String[] args) { final int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) System.out.print ("*");
System.out.println(); } }}
![Page 46: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/46.jpg)
46
//********************************************************************// Stars.java Author: Lewis/Loftus//// Demonstrates the use of nested for loops.//********************************************************************
public class Stars{ //----------------------------------------------------------------- // Prints a triangle shape using asterisk (star) characters. //----------------------------------------------------------------- public static void main (String[] args) { final int MAX_ROWS = 10;
for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) System.out.print ("*");
System.out.println(); } }}
Output*******************************************************
![Page 47: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/47.jpg)
47
Outline
Enumerated Types
The while Statement
do while Statement
The for Statement
Declaring and Using Arrays
![Page 48: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/48.jpg)
48
Arrays• An array is an ordered list of values:
0 1 2 3 4 5 6 7 8 9
79 87 94 82 67 98 87 81 74 91
An array of size N is indexed from zero to N-1
scores
The entire arrayhas a single name
Each value has a numeric index
This array holds 10 values that are indexed from 0 to 9
![Page 49: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/49.jpg)
49
Arrays• A particular value in an array is referenced using
the array name followed by the index in brackets
• For example, the expression
scores[2]
refers to the value 94 (the 3rd value in the array)
• That expression represents a place to store a single integer and can be used wherever an integer variable can be used
![Page 50: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/50.jpg)
50
Arrays• For example, an array element can be
assigned a value, printed, or used in a calculation:
scores[2] = 89;
scores[first] = scores[first] + 2;
mean = (scores[0] + scores[1])/2;
System.out.println ("Top = " + scores[5]);
pick = scores[rand.nextInt(11)];
![Page 51: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/51.jpg)
51
Arrays• The values held in an array are called array
elements
• An array stores multiple values of the same type – the element type
• The element type can be a primitive type or an object reference
• Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc.
![Page 52: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/52.jpg)
52
Arrays• In Java, the array itself is an object that must be
instantiated• Another way to depict the scores array:
scores 79
87
94
82
67
98
87
81
74
91
The name of the arrayis an object reference
variable
![Page 53: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/53.jpg)
53
Declaring Arrays• The scores array could be declared as follows:
int[] scores = new int[10];
• The type of the variable scores is int[] (an array of integers)
• Note that the array type does not specify its size, but each object of that type has a specific size
• The reference variable scores is set to a new array object that can hold 10 integers
![Page 54: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/54.jpg)
54
Declaring Arrays• Some other examples of array declarations:
int[] weights = new int[2000];
double[] prices = new double[500];
boolean[] flags;flags = new boolean[20];
char[] codes = new char[1750];
![Page 55: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/55.jpg)
55
//********************************************************************// BasicArray.java Author: Adapted from Lewis/Loftus//// Demonstrates basic array declaration and use.//********************************************************************
public class BasicArray{ //----------------------------------------------------------------- // Creates an array, fills it with various integer values, // modifies one value, then prints them out. //----------------------------------------------------------------- public static void main (String[] args) { final int LIMIT = 15, MULTIPLE = 10;
int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value // Print the array values for (int index = 0; index < LIMIT; index++) System.out.print (value + " "); }}
![Page 56: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/56.jpg)
56
//********************************************************************// BasicArray.java Author: Adapted from Lewis/Loftus//// Demonstrates basic array declaration and use.//********************************************************************
public class BasicArray{ //----------------------------------------------------------------- // Creates an array, fills it with various integer values, // modifies one value, then prints them out. //----------------------------------------------------------------- public static void main (String[] args) { final int LIMIT = 15, MULTIPLE = 10;
int[] list = new int[LIMIT]; // Initialize the array values for (int index = 0; index < LIMIT; index++) list[index] = index * MULTIPLE; list[5] = 999; // change one array value // Print the array values for (int index = 0; index < LIMIT; index++) System.out.print (value + " "); }}
Output0 10 20 30 40 999 60 70 80 90 100 110 120 130 140
![Page 57: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/57.jpg)
57
Basic Array Example
![Page 58: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/58.jpg)
58
Quick CheckWrite an array declaration to represent the ages of 100 children.
Write code that prints each value in an array of integers named values.
![Page 59: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/59.jpg)
59
Quick CheckWrite an array declaration to represent the ages of 100 children.
Write code that prints all the 100 values of an array of integers named values.
int[] ages = new int[100];
int i;
for (int i=0; i<100; i++)
System.out.println(value[i]);
![Page 60: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/60.jpg)
60
Bounds Checking• Once an array is created, it has a fixed size
• An index used in an array reference must specify a valid element
• That is, the index value must be in range 0 to N-1
• The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds
• This is called automatic bounds checking
![Page 61: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/61.jpg)
61
Bounds Checking• For example, if the array codes can hold 100
values, it can be indexed from 0 to 99
• If the value of count is 100, then the following reference will cause an exception to be thrown:
System.out.println(codes[count]);
• It’s common to introduce off-by-one errors when using arrays:
for (int index=0; index <= 100; index++)codes[index] = index*50 + epsilon;
problem
![Page 62: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/62.jpg)
62
Bounds Checking• Each array object has a public constant called length that stores the size of the array
• It is referenced using the array name:scores.length
• Note that length holds the number of elements, not the largest index
• See ReverseOrder.java
• See LetterCounter.java
![Page 63: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/63.jpg)
63
//********************************************************************// ReverseOrder.java Author: Lewis/Loftus//// Demonstrates array index processing.//********************************************************************
import java.util.Scanner;
public class ReverseOrder{ //----------------------------------------------------------------- // Reads a list of numbers from the user, storing them in an // array, then prints them in the opposite order. //----------------------------------------------------------------- public static void main (String[] args) { Scanner scan = new Scanner (System.in);
double[] numbers = new double[10];
System.out.println ("The size of the array: " + numbers.length);
continue
![Page 64: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/64.jpg)
64
continue
for (int index = 0; index < numbers.length; index++) { System.out.print ("Enter number " + (index+1) + ": "); numbers[index] = scan.nextDouble(); } System.out.println ("The numbers in reverse order:");
for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " "); }}
![Page 65: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/65.jpg)
65
continue
for (int index = 0; index < numbers.length; index++) { System.out.print ("Enter number " + (index+1) + ": "); numbers[index] = scan.nextDouble(); } System.out.println ("The numbers in reverse order:");
for (int index = numbers.length-1; index >= 0; index--) System.out.print (numbers[index] + " "); }}
Sample RunThe size of the array: 10Enter number 1: 18.36Enter number 2: 48.9Enter number 3: 53.5Enter number 4: 29.06Enter number 5: 72.404Enter number 6: 34.8Enter number 7: 63.41Enter number 8: 45.55Enter number 9: 69.0Enter number 10: 99.18The numbers in reverse order:99.18 69.0 45.55 63.41 34.8 72.404 29.06 53.5 48.9 18.36
![Page 66: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/66.jpg)
66
//********************************************************************// LetterCount.java Author: Adapted from Lewis/Loftus//// Demonstrates the relationship between arrays and strings.//********************************************************************
import java.util.Scanner;
public class LetterCounter{ //----------------------------------------------------------------- // Reads a sentence from the user and counts the number of // uppercase, lowercase and non-alphabetic letters contained in it. //----------------------------------------------------------------- public static void main (String[] args) {
int LowerCase =0; int UpperCase =0; int NonAlphabetic =0;
char current; // the current character being processed Scanner scan = new Scanner (System.in);
System.out.println ("Enter a sentence:"); String line = scan.nextLine();
continue
![Page 67: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/67.jpg)
67
continue
System.out.println ("Enter a sentence:"); String line = scan.nextLine();
for (int ch = 0; ch < line.length(); ch++) { current = line.charAt(ch);
if (current >= 'A' && current <= 'Z') UpperCase++; else { if (current >= 'a' && current <= 'z') LowerCase++; else NonAlphabetic++; } } // Print the results System.out.println ("Number of Uppercase characters: " + UpperCase); System.out.println ("Number of Lowercase characters: " + LowerCase); System.out.println ("Number of Non-alphabetic characters: ” + NonAlphabetic); }}
Sample RunEnter a sentence:Java Programing LanguageUppercase characters: 3Lowercase characters: 19Non-alphabetic characters: 2
![Page 68: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/68.jpg)
68
Alternate Array Syntax• The brackets of the array type can be
associated with the element type or with the name of the array
• Therefore the following two declarations are equivalent:
double[] prices;
double prices[];
• The first format generally is more readable and should be used
![Page 69: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/69.jpg)
69
Initializer Lists• An initializer list can be used to instantiate and
fill an array in one step
• The values are delimited by braces and separated by commas
• Examples:
int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476};
char[] grades = {'A', 'B', 'C', 'D', ’F'};
![Page 70: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/70.jpg)
70
Initializer Lists• Note that when an initializer list is used:
– the new operator is not used– no size value is specified
• The size of the array is determined by the number of items in the list
• An initializer list can be used only in the array declaration
• See Primes.java
![Page 71: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/71.jpg)
71
//********************************************************************// Primes.java Author: Adapted from Lewis/Loftus//// Demonstrates the use of an initializer list for an array.//********************************************************************
public class Primes{ //----------------------------------------------------------------- // Stores some prime numbers in an array and prints them. //----------------------------------------------------------------- public static void main (String[] args) { int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " + primeNums.length);
System.out.println ("The first few prime numbers are:");
for (int i=0; i < primeNums.length; i++) System.out.print (prime + " "); }}
![Page 72: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/72.jpg)
72
//********************************************************************// Primes.java Author: Lewis/Loftus//// Demonstrates the use of an initializer list for an array.//********************************************************************
public class Primes{ //----------------------------------------------------------------- // Stores some prime numbers in an array and prints them. //----------------------------------------------------------------- public static void main (String[] args) { int[] primeNums = {2, 3, 5, 7, 11, 13, 17, 19}; System.out.println ("Array length: " + primeNums.length);
System.out.println ("The first few prime numbers are:");
for (int i=0; i < primeNums.length; i++) System.out.print (prime + " "); }}
OutputArray length: 8The first few prime numbers are:2 3 5 7 11 13 17 19
![Page 73: Lesson 5](https://reader035.vdocuments.us/reader035/viewer/2022062711/55c6edbdbb61eb77608b46c9/html5/thumbnails/73.jpg)
73
Arrays as Parameters• An entire array can be passed as a parameter to
a method
• Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other
• Therefore, changing an array element within the method changes the original
• An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type