Lab06 Arrays&Enumerated
Lab06 Arrays&Enumerated
Lab #6
1
Contents
• Arrays
• Multidimensional Arrays
• Enumerated Types
2
Arrays
• Background
– Programmers often need the ability to represent a group of values as a
list
• List may be one-dimensional or multidimensional
3
Basic terminology
• An array is composed of elements
• Elements in an array have a common name
– Example: a[3] = 5;
– The common name is ‘a’
• The entire array is referenced through the common name
• Array elements are of the same type – the base type
• Elements of an array are referenced by subscribing (indexing) the
common name
4
Arrays (Contd)
• Defining arrays Defines the Array identifier c
– char[] c; Array object variable c is
un-initialized
c
5
Arrays (Contd)
• Creating an array:
int[] foo = new int[10];
• Accessing an array:
foo[3] = 7;
System.out.println(foo[1]);
• Creating an array:
String[] bar = new String[10];
• Accessing an array:
bar[3] = “qux”;
System.out.println(bar[1]);
6
An array example
int[] v = new int[10];
int i = 7;
int j = 2;
int k = 4;
v[0] = 1;
v[i] = 5;
v[j] = v[i] + 3;
v[j+1] = v[i] + v[0];
v[j+2] = 3;
v[8] = 12;
v 1 0 8 6 3 0 0 5 12 0
v[0] v[1] v[2] v[3] v[4] v[5] v[6] v[7] v[8] v[9]
7
Java array features
• Base (element) type can be any type
• Size of array can be specified at run time
double[] score = new double[count];
• Index type is integer and the index range must be 0 to n-1
– Where n is the number of elements
– Just like Strings indexing!
• Automatic bounds checking
– Ensures any reference to an array element is valid
• Array is an object
– Has features common to all other objects
8
Explicit initialization
• An array can be initialized when it is declared
• Example
String[] puppy = {“pika”, “mila”, “arlo”, “mikki”};
int[] unit = { 1 };
• Equivalent to
String[] puppy = new String[4];
puppy[0] = “pika”; puppy[1] = “mila”;
puppy[2] = “arlo”; puppy[3] = “nikki”;
9
Variable-size Declaration
• In Java, we are not limited to fixed-size array declaration
• The following code prompts the user for the size of an array and
declares an array of designated size:
System.out.print("Size of an array:"));
size= scanner.nextInt( );
10
Array length
• Member length
– Size of the array
for(int i = 0; i < puppy.length; ++i) {
System.out.println(puppy[i]);
}
11
Array manipulation
• The most natural way to manipulate items in an array is to use
the for loop
• Basic for loop
for(int index = 0; index < arr.length; index++) {
//perform array manipulation tasks here
System.out.println(arr[index]);
}
– The for loop uses an index from 0 to the end of the array
12
Array manipulation (Contd)
• You can use other loops with array
– While loop
int i = 0;
while(i < arr.length) {
System.out.println(arr[i]);
}
– Do While loop
int j = 0;
do {
System.out.println(arr[j]);
j++;
} while (j < arr.length);
13
An array example
14
Arrays and References
• Like class types, a variable of an array type holds a reference
– Arrays are objects
– A variable of an array type holds the address of where the array object is
stored in memory
– Array types are (usually) considered to be class types
15
Use of = and == with Arrays
• Because an array variable contains the memory address of the
array it names, the assignment operator (=) only copies this
memory address
– It does not copy the values of each indexed variable
– Using the assignment operator will make two array variables be different
names for the same array
b = a;
– The memory address in a is now the same as the memory address in b :
They reference the same array
16
Use of = and == with Arrays (Contd)
• A for loop is usually used to make two different arrays have the
same values in each indexed position:
int i;
for (i = 0; (i < a.length) && (i < b.length); i++)
b[i] = a[i];
• Note that the above code will not make b an exact copy of a,
unless a and b have the same length
17
Arrays with a Class Base Type
• The base type of an array can be a class type
18
Arrays with a Class Base Type (Contd)
19
Arrays (Contd)
There is no object
20
Arrays (Contd)
Creates an object
21
Passing an Array as a parameter
22
Methods That Return an Array
• In Java, a method may also return an array
– The return type is specified in the same way that an array parameter is
specified
23
Self-Test (1)
• 프로젝트 명: Project06_1
– git commit –m “Project06_1”
• 시험 점수의 평균값과 각 점수의 평균값과의 차이값을 출력하는
TestScores 클래스를 구현할 것
• scores 배열에 입력값을 입력 받는 fillArray 메소드를 작성할 것
– 점수 배열을 인자로 받음
– 음수값을 입력 받거나, 입력값의 개수가 배열 최대 크기를 초과할 경우 종
료
– 입력값의 개수를 반환함
• 각 점수와 평균값의 차이값을 반환하는 showDifference 메소드를 작성
할것
– 점수 배열과 입력값의 개수를 인자로 받음
– 메소드 내에서 평균값을 computeAverage 메소드를 호출함
– 이를 이용하여 각 점수와 평균값과의 차이값을 출력함
24
Self-Test (1) (Contd)
• scores의 평균값을 반환하는 computeAverage
– 점수 배열과 입력값의 개수를 인자로 받음
– 점수 배열내 원소의 총합과 인자로 받은 입력값의 개수를 나누어 평균값을
반환함
25
Multidimensional arrays
• Many problems require information be organized as a two-
dimensional or multidimensional list
• Examples
– Matrices
– Graphical animation
– Economic forecast models
– Map representation
– Time studies of population change
– Microprocessor design
26
Multidimensional arrays (Contd)
• A multidimensional array is basically an array of arrays
27
Example
• Segment
int[][] m = new int[3][4];
• Products
m 0 0 0 0
0 0 0 0 0 0 0 0
28
Multidimensional array visualization
0 0 0 0
0 4 0 0
29
Accessing an Element
• An element in a two-dimensional array is accessed by its row and
column index
30
Sample 2-Dimensional Array Processing
average[i] += payScaleTable[i][j];
}
31
Sample 2-Dimensional Array Processing (Contd)
32
Enumerated Types
• Starting with version 5.0, Java permits enumerated types
– An enumerated type is a type in which all the values are given in a
(typically) short list
• The definition of an enumerated type is normally placed outside
of all methods in the same place that named constants are
defined:
33
Enumerated Types Example
• Given the following definition of an enumerated type:
34
Enumerated Types Usage
• Just like other types, variable of this type can be declared and
initialized at the same time:
WorkDay meetingDay = WorkDay.THURSDAY;
– Note that the value of an enumerated type must be prefaced with the
name of the type
• The value of a variable or constant of an enumerated type can be
output using println
– The code
System.out.println(meetingDay);
– Will produce the following output:
THURSDAY
– As will the code:
System.out.println(WorkDay.THURSDAY);
– Note that the type name WorkDay is not output
35
Enumerated Types Usage (Contd)
• Although they may look like String values, values of an
enumerated type are not String values
• However, they can be used for tasks which could be done by
String values and, in some cases, work better
– Using a String variable allows the possibility of setting the variable to a
nonsense value
– Using an enumerated type variable constrains the possible values for
that variable
– An error message will result if an attempt is made to give an enumerated
type variable a value that is not defined for its type
36
Enumerated Types Usage (Contd)
• Two variables or constants of an enumerated type can be
compared using the equals method or the == operator
• However, the == operator has a nicer syntax
if (meetingDay == availableDay)
System.out.println(“Meeting will be on schedule.”);
if (meetingDay == WorkDay.THURSDAY)
System.out.println(“Long weekend!);
37
An Enumerated Type Example
38
Some Methods included with Every
Enumerated Type
39
Some Methods included with Every
Enumerated Type (Contd)
40
Some Methods included with Every
Enumerated Type (Contd)
41
Programming Tip: Enumerated Types in
switch Statements
• Enumerated types can be used to control a switch statement
– The switch control expression uses a variable of an enumerated type
– Case labels are the unqualified values of the same enumerated type
• The enumerated type control variable is set by using the static
method valueOf to convert an input string to a value of the
enumerated type
– The input string must contain all upper case letters, or be converted to
all upper case letters using the toUpperCase method
42
Enumerated Types in switch Statements
Example
43
Enumerated Types in switch Statements
Example (Contd)
44
Enumerated Types in switch Statements
Example (Contd)
45
Pitfall: An Array of Characters Is Not a String
54
Self-Test (2)
numberOfStudnets
student
[0] [1]
numberOfQuizzes Average[]
[0] 10 5 7.5
[1] 10 10 10.0
[2] 10 20 15.0
quiz
10 11.6666
Average[]
55
Self-Test (2)
56
Self-Test (2)
57
Self-Test (2)
• 최종 결과화면
58