0% found this document useful (0 votes)
27 views

Lab06 Arrays&Enumerated

Uploaded by

Jinwoo Song
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Lab06 Arrays&Enumerated

Uploaded by

Jinwoo Song
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Object – Oriented Programming

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

– An array is a data structure used to process a collection of data that is


all of the same type

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

– int[] value = new int[10]; Defines and initializes the Array


Array object variable value
0 0 0 0 0 0 0 0 0 0 references a new ten element
value list of integers
Each of the integers is default
initialized to 0

• Generally declare Arrays in java as follows


BaseType[] ArrayName = new BaseType[size];

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

int[] unit = new int[1];


unit[0] = 1;

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:

Scanner scanner = new Scanner(System.in);


int size;
int[] number;

System.out.print("Size of an array:"));
size= scanner.nextInt( );

number = new int[size];

10
Array length
• Member length
– Size of the array
for(int i = 0; i < puppy.length; ++i) {
System.out.println(puppy[i]);
}

• Note that length is a field, not a method!


– i.e., It is not puppy.length();

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

– This is useful initializing your array with default values


– For example 0’s 0 0 0 0 0 0

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

Date[] holidayList = new Date[20];

• The above example creates 20 indexed variables of type Date


– It does not create 20 objects of the class Date
– Each of these indexed variables are automatically initialized to null
– Any attempt to reference any them at this point would result in a “null
pointer exception” error message

18
Arrays with a Class Base Type (Contd)

• Like any other object, each of the indexed variables requires a


separate invocation of a constructor using new (singly, or perhaps
using a for loop) to create an object to reference
holidayList[0] = new Date();

holidayList[19] = new Date();
OR
for(int i = 0; i < holidayList.length; i++)
holidayList[i] = new Date();

• Each of the indexed variables can now be referenced since each


holds the memory address of a Date object

19
Arrays (Contd)

There is no object

20
Arrays (Contd)

Creates an object

21
Passing an Array as a parameter

To pass an array as a parameter


simply declare the identifier.
You do not need to enter the size
of the array

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

public static int[] incrementArray(int[] a, int increment) {


int[] temp = new int[a.length];
int i;
for (i=0; i < a.length; i++) {
temp[i] = a[i] + increment;
}
return temp;
}

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

• In a multidimensional array each array item represents the pointer


to another array

27
Example
• Segment
int[][] m = new int[3][4];

• Products

m[0] m[1] m[2] m[2][0] m[2][1] m[2][2] m[2][3]

m 0 0 0 0

m[1][0] m[1][1] m[1][2] m[1][3]

0 0 0 0 0 0 0 0

m[0][0] m[0][1] m[0][2] m[0][3]

28
Multidimensional array visualization

• A multi-dimensional array declaration

declaring the array


int[][] m = new int[3][4];

accessing the array


m[2][1] = 4;

• How we visualize it: 0 0 0 0

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

• Multidimensional arrays are usually processed using nested loops


• The outer loop iterates the rows
• The inner loop iterates the items of each row (i.e. column)
double[ ] average = { 0.0, 0.0, 0.0, 0.0 };

for (int i = 0; i < payScaleTable.length; i++) {

for (int j = 0; j < payScaleTable[i].length; j++) {

average[i] += payScaleTable[i][j];
}

average[i] = average[i] / payScaleTable[i].length;

31
Sample 2-Dimensional Array Processing (Contd)

• The basic structure of 2D array processing code

arrayType[][] arrayName = new arrayType[numRows][numCols]

for (int i = 0; i < arrayName.length; i++) {

for (int j = 0; j < arrayName[i].length; j++) {

//Perform actions in here


// e.g. System.out.print(arrayName[i][j])
}

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:

enum TypeName {VALUE_1, VALUE_2, ……, VALUE_N};

– Note that a value of an enumerated type is a kind of named constant


and so, by convention, is spelled with all uppercase letters
– As with any other type, variables can be declared of an enumerated type

33
Enumerated Types Example
• Given the following definition of an enumerated type:

enum WorkDay {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY};

• A variable of this type can be declared as follows:

WorkDay meetingDay, availableDay;

• The value of a variable of this type can be set to one of the


values listed in the definition of the type, or else to the special
value null:
meetingDay = WorkDay.THURSDAY;
availableDay = null;

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

• An array of characters is conceptually a list of


characters, and so is conceptually like a string
• However, an array of characters is not an object
of the class String
char[] a = {'A', 'B', 'C'};
String s = a; //Illegal!
• An array of characters can be converted to an
object of type String, however

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 6-46


Pitfall: An Array of Characters Is Not a String

• The class String has a constructor that has a single


parameter of type char[]
String s = new String(a);
– The object s will have the same sequence of characters as
the entire array a ("ABC"), but is an independent copy
• Another String constructor uses a subrange of a
character array instead
String s2 = new String(a,0,2);
– Given a as before, the new string object is "AB"

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 6-47


Pitfall: An Array of Characters Is Not a String

• An array of characters does have some things


in common with String objects
– For example, an array of characters can be output
using println
System.out.println(a);
– Given a as before, this would produce the output
ABC

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 6-48


Arguments for the Method main
• Here is a program that expects three string
arguments:
public class SomeProgram
{
public static void main(String[] args)
{
System.out.println(args[0] + " " +
args[2] + args[1]);
}
}
• Note that if it needed numbers, it would have to
convert them from strings first

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 6-49


Arguments for the Method main
• If a program requires that the main method be
provided an array of strings argument, each element
must be provided from the command line when the
program is run
java SomeProgram Hi ! there
– This will set args[0] to "Hi", args[1] to "!", and
args[2] to "there"
– It will also set args.length to 3
• When SomeProgram is run as shown, its output
will be:
Hi there!

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 6-50


Privacy Leaks with Array Instance Variables

• If an accessor method does return the contents of an


array, special care must be taken
– Just as when an accessor returns a reference to any private
object
public double[] getArray()
{
return anArray;//BAD!
}
– The example above will result in a privacy leak

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 6-51


Privacy Leaks with Array Instance Variables

• The previous accessor method would simply return a


reference to the array anArray itself
• Instead, an accessor method should return a reference
to a deep copy of the private array object
– Below, both a and count are instance variables of the class
containing the getArray method
public double[] getArray()
{
double[] temp = new double[count];
for (int i = 0; i < count; i++)
temp[i] = a[i];
return temp
}

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 6-52


Privacy Leaks with Array Instance Variables

• If a private instance variable is an array that has a class as its


base type, then copies must be made of each class object in
the array when the array is copied:
public ClassType[] getArray()
{
ClassType[] temp = new ClassType[count];
for (int i = 0; i < count; i++)
temp[i] = new ClassType(someArray[i]);
return temp;
}

Copyright © 2010 Pearson Addison-Wesley. All rights reserved. 6-53


Self-Test (2)
• 프로젝트 명: Project06_2
– git commit –m “Project06_2”
– 당일 밤 12시까지 제출
• 학생의 수와 퀴즈의 개수를 입력 받아 각 학생들의 평균점수, 각 퀴즈별
평균점수를 구하는 GradeBook 클래스 구현
• GradeBook() 생성자
– 학생 수와 퀴즈의 개수를 입력 받음
– 퀴즈 점수를 저장하는 2차원 배열 변수 grade를 초기화할 것
– grade 변수의 원소 값들을 Scanner 클래스를 통해 학생들의 퀴즈 점수로 입
력 받을 것
• fillStudentAverage() 메소드
– 학생들의 전체 퀴즈 평균 점수를 studentAverage 1차원 변수에 해당하는
index에 저장
• fillQuizAverage() 메소드
– 퀴즈들의 평균 점수를 quizeAverage 1차원 변수에 해당하는 index에 저장

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)

• 학생 2명, 퀴즈 3개 즉 학생1이 퀴즈 1,2,3을 보고 학생 2가 퀴즈 1,2,3


을봄

56
Self-Test (2)

• 각각의 점수를 입력.

57
Self-Test (2)

• 최종 결과화면

58

You might also like