1 Chap8: Arrays. 2 배열의 종류 같은 자료 형들끼리 모 아둘 수 있는 묶음이 하 나밖에 없는 경우 1 차원 배열이 여러 개 있는 경우 boolean,char, int 등과 같은 기본 자료 형의 배열 객체를 참조하는 참조변수들의 묶음.

Slides:



Advertisements
Similar presentations
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Advertisements

Chapter 8: Arrays.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Chapter 11 Arrays. Introduction Array: An ordered collection of values with two distinguishing characters: – Ordered and fixed length – Homogeneous. Every.
Arrays.
Chapter 7 – Arrays.
Arrays Chapter 6 Chapter 6.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Arrays Horstmann, Chapter 8. arrays Fintan Array of chars For example, a String variable contains an array of characters: An array is a data structure.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Class design. int month; int year class Month Defining Classes A class contains data declarations (state) and method declarations (behaviors) Data declarations.
Review Java.
© The McGraw-Hill Companies, 2006 Chapter 7 Implementing classes.
More Arrays Length, constants, and arrays of arrays By Greg Butler.
Java Unit 9: Arrays Declaring and Processing Arrays.
Arrays. Exam 1 1. Java source and executable files have the following extensions? a..java and.class b..src and.class c..javadoc and.exe d..list and.exe.
One Dimensional Array. Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection.
Grouping Related Items
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Programming Fundamentals I (COSC-1336), Lecture 8 (prepared after Chapter 7 of Liang’s 2011 textbook) Stefan Andrei 4/23/2017 COSC-1336, Lecture 8.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved
Introduction to Collections Arrays. Collections Collections allow us to treat a group of values as one collective entity. The array is a collection of.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Arrays Pepper. What is an Array A box that holds many of the exact same type in mini-boxes A number points to the mini-box The number starts at 0 String.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Computer Programming 12 Mr. Jean April 24, The plan: Video clip of the day Upcoming Quiz Sample arrays Using arrays More about arrays.
Data Structures and Algorithms Lecture 1 Instructor: Quratulain Date: 1 st Sep, 2009.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Introduction to Java Java Translation Program Structure
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Lecture 101 CS110 Lecture 10 Thursday, February Announcements –hw4 due tonight –Exam next Tuesday (sample posted) Agenda –questions –what’s on.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
8-1 Chapter-7 Part1 Introduction to Arrays –Array Types –Creating/Declaring Arrays –Initializing Arrays –Processing Array Contents –Passing Arrays as Arguments.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Comparing ArrayLists and Arrays. ArrayLists ArrayLists are one type of flexible-size collection classes supported by Java –ArrayLists increase and decrease.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Midterm Review Tami Meredith. Primitive Data Types byte, short, int, long Values without a decimal point,..., -1, 0, 1, 2,... float, double Values with.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Chapter 5 Arrays F Introducing Arrays F Declaring Array Variables, Creating Arrays, and Initializing Arrays F Passing Arrays to Methods F Copying Arrays.
Arrays Chapter 7.
Topic: Classes and Objects
Chapter 8 – Arrays and Array Lists
[ 4.00 ] [ Today’s Date ] [ Instructor Name ]
An Introduction to Java – Part I, language basics
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
Introduction to Objects
Dr. Sampath Jayarathna Cal Poly Pomona
Suggested self-checks: Section 7.11 #1-11
Java Programming Language
Dr. Sampath Jayarathna Cal Poly Pomona
Presentation transcript:

1 Chap8: Arrays

2 배열의 종류 같은 자료 형들끼리 모 아둘 수 있는 묶음이 하 나밖에 없는 경우 1 차원 배열이 여러 개 있는 경우 boolean,char, int 등과 같은 기본 자료 형의 배열 객체를 참조하는 참조변수들의 묶음

3 One-Dimensional Arrays Definition: –An array is a data structure that holds some fixed quantity of multiple data items (elements) of the same data type. Arrays are objects, and they are created with the new keyword.

4 One-Dimensional Arrays 배열을 선언하고 생성하는 절차 – 선언과 동시에 생성 가능 int[] numbers = new int[6] – 어떠한 자료의 배열도 생성가능하다. float[] distances = new float[20]; Char[] letters = new char[50]; Date[] dates = new Date[30]; – 배열의 크기를 표시할 때 상수 ( 또는 일반 변수 ) 사용 가능 final int SIZE = 31; int SIZE2=40; double[] temperature = new double[SIZE]; double[] temperature2 = new double[SIZE2]; – 배열은 일단 생성되면 그 크기를 변경할 수 없다.

5 One-Dimensional Arrays [ 주의 ] 배열의 선언시에 크기 지정은 안됨 –int matrix[5]; // 잘못됨 –int matrix[5] = {1,2,3,4,5}; // 잘못됨 배열의 사용 – 다음과 같은 코드에서 int[] numbers = new int[6] – 첫 원소는 numbers[0], 마지막 원소는 numbers[5] – 예 numbers[0] = 0; numbers[3] = 30;

6 One-Dimensional Arrays 또 다른 참조 변수 선언 방법 – 자바에서는 C 언어와 유사하게 배열 참조 변수를 선언할 수 있다. int[] values; // ① 자바 방식 int values[]; // ② C 언어 유사 방식 위 두 가지는 100% 동일 – 여러 개의 배열 변수 선언시 주의 int[] values, grades; // 2 개의 변수 모두 배열로서 선언됨 int values, grades[]; // values 는 int 변수, grades 만 배열 변수 int values[], grades[]; // 2 개의 변수 모두 배열로서 선언됨

7 One-Dimensional Arrays int[] number = new int[6]; int x = 6; number[1] = 7; number[3] = number[x - 5] + 2; int[] s = number; int[] number == a1 : int[6] a int[] number == a1 : int[6] int[] s == a

8 배열 생성 과정 1) 배열 선언 char[] ch; 또는 char ch[]; 2) 배열 생성 ch = new char[4]; 3) 배열 초기화 ch[0]=‘J’; ch[1]=‘a’; ch[2]=‘v’; ch[3]=‘a’;

9 Default Initialization An array of numeric values is initialized with all zero values An array of booleans is initialized with false values An array of objects is initialized to null values, where null means “no value.”

10 More Examples int[] r = new int[6];... r[0] = 1; for ( int i=0; i < r.length-1; i=i+1 ) { r[i+1] = r[i] * 2; } int[] r = new char[]{1,2,4,8,16,32};  int[] r; r = new char[] {1,2,4,8,16,32}; int[] r = {1, 2, 4, 8, 16, 32}; a int[] r == a1 : int[6]

11 More Examples 배열의 크기 for-each 루프 –Java 1.5 부터 지원 – 위 코드는 반복이 진행되면서 첫 번째 원소부터 마지막 원소까지 차례대로 value 에 대입되면서 for 문의 몸체가 수행된다. int[] numbers = new int[100]; for(int i=0; i < numbers.length; i++) numbers[i] = (int)(Math.random()*1000); 배열의 크기는 length 라는 필드로 알 수 있습니다. for (int value: numbers) System.out.println(value);

12 More Examples for~each 활용 예제 – 배열의 모든 원소를 처리하는 경우엔 for ~ each 구문이 좋다. 배열의 크기에 신경쓰지 않아도 되고 인덱스 변수 생성이 필요 없다. –for~each 구문이 적합하지 않은 경우 배열 원소의 값을 변경하는 경우 역순으로 배열 원소를 처리하는 경우 일부 원소만을 출력하는 경우 두 개 이상의 배열을 처리하는 경우 public class Test { public static void main(String[] args) { String[] strings = { "Java", "C", "C++" }; for (String s : strings) System.out.println(s); }

13 Method & Array Arrays can be parameters to methods and can be results from methods. (send the address of the array object) public double[] inverse(double[] r) { int size = r.length; double[] answer = new double[size]; for ( int i = 0; i != size; i = i+1 ) { answer[(size - 1) - i)] = r[i]; } return answer; } double[] d = {2.3, -4.6, 8, 3.14}; double[] e = inverse(d); it is the address of the array (here, the address of the four-element array named by d ) which is bound to the formal parameter, r. Inside the method, a second array is created, and the second array gets copies of the elements in the first array. When the method finishes, it returns as its answer the address of the second array.

14 Method & Array 메소드의 매개 변수로 배열 전달 –call by value 로 처리 – 하지만 주소가 복사되기 때문에 call by reference 효과가 발생

15 Method & Array public class ScoreTest1 { final static int STUDENTS = 5; public static void main(String[] args) { int[] scores = new int[STUDENTS]; getValues(scores); getAverage(scores); } private static void getValues(int[] array) { Scanner scan = new Scanner(System.in); for (int i = 0; i < array.length; i++) { array[i] = i; } private static void getAverage(int[] array) { int total = 0; for (int i = 0; i < array.length; i++) total += array[i]; System.out.println(" 평균은 " + total / array.length + " 입니다 "); }

16 Method & Array 메소드의 반환값으로 배열 전달 – 메소드가 반환값으로 배열을 전달 할 수 있다. – 이 때에도 배열 참조값이 복사됨 import java.util.Scanner; public class Test { public static void main(String[] args) { int[] array; array = getData(); printData(array); } private static int[] getData() { int[] testData = { 10, 20, 30, 40, 50 }; return testData; } private static void printData(int[] array) { for (int i = 0; i < array.length; i++) System.out.println(array[i]); }

17 Array of Object 객체들의 배열에서는 객체에 대한 참조값을 각 원소가 저장 – 배열 객체 생성 newCar[] cars = new Car[6]; – 배열에 객체 할당 cars[0] = new Cars(); cars[1] = new Cars(); –For 루프를 이용한 객체 할당

18 Array of Object (Example) class Car { public int speed // 속도 public int mileage // 주행거리 public String color // 색상 public Car() { speed = mileage = 0; color = "red"; } public void speedUp() { // 속도 증가 메소드 speed += 10; } public String toString() { // 객체의 상태를 문자열로 반환하는 메소드 return " 속도 : " + speed + " 주행거리 : " + mileage + " 색상 : " + color; }

19 Array of Object (Example) public class CarTest { public static void main(String[] args) { final int NUM_CARS = 5; Car[] cars = new Car[NUM_CARS]; for (int i = 0; i < cars.length; i++) { cars[i] = new Car(); cars[i].speedUp(); System.out.println(cars[i]); }

20 Use of Arrays Collecting Input Data within Arrays –Example: Vote Counting (See Figure 8.1, class VoteCounting ) Translation Tables –Example: Substitution Code (See class SubsitutionCode ) Arrays of Objects –Example: Bank Account (See next slide) –An array can be partially filled with objects for ( int i = 0; i != account.length; i = i+1 ) { if ( bank[i] != null ) { System.out.println("Balance of account " + i + " is " + account[i].balanceOf() ); }

21 Use of Arrays (cont’d) BankAccount[] bank = new BankAccount[100]; BankAccount[] bank == a1 : BankAccount[100] a1 null … BankAccount[] bank == a1 : BankAccount[100] a1 nulla2…null bank[1] = new BankAccount(20); a2 : BankAccount int balance == public void deposit(int amount) public boolean withdraw(int amount) 20

22 Case Study: Database What is a database? –a large collection of information. –Ex: a company’s sales records or its customer accounts or its payroll information –in OO terms: a “container” into which objects are inserted, located, and removed. What is a record? –the objects that are stored in a database. –uniquely identified by its key.

23 Build a Database in Java 1.Keys are objects. 2.Records are objects, and a record holds as one of its attributes (the address of) its key object. 3.A database is a kind of “array” of record objects; it must have methods for inserting a record, finding a record, and deleting a record. 4.When the database's user wishes to insert a record into the database, she calls the databases' insert method, supplying the record as the argument; when she wishes to find a record, she calls the find method, supplying a key object as an argument; when she wishes to delete a record, the calls the delete method, supplying a key object as an argument

24

25 Architecture Database Record Key insert find delete getKey(): Key equals(Key y) : boolean 1 *

26 Specification insert(Record r) : boolean Attempts to insert the record, r, into the database. Returns true if the record is successfully added, false otherwise. find(Key k) : Record Attempts to locate the record whose key has value k. If successful, the address of the record is returned, otherwise, null is returned. Methods class Database a container for data items, called Records delete(Key k) : boolean Deletes the record whose key has value k. If successful, true is returned; if no record has key k, false is returned.

27 keyOf(): Key Returns the key that uniquely identifies the record. Methods class Record a data item that can be stored in a database equals(Key m) : boolean Compares itself to another key, m, for equality. If this key and m are same key value, then true is returned; if m is a different key value, then false is returned. lessthan(Key m) : boolean Compares itself to another key, m, for lessthan. If this object's own key is a lesser key value than m, true is returned; otherwise, false is returned. Methods class Key an identification, or “key,” value

28 Implementation class Database (Figure 8.4) class Record (Figure 8.5) for Bank Account class Key (Figure 8.5) for Bank Account class Record (Figure 8.6) for Book class Key (Figure 8.6) for Book

29 Execution Here is a short code fragment that constructs a database for a library and inserts a book into it: Database library = new Database(50000); Record book = new Book( new Key("QA", 76.8), "Charles Dickens", "Great Expectations", 1860 ); library.insert(book); // We might locate the book this way: Key lookup_key = new Key("QA", 76.8); book = library.find(lookup_key); // We can delete the book, if necessary: boolean deleted = library.delete(lookup_key);

30 Case Study: Playing Pieces of Card Games Deck Card new Card() : Card suit count 1*

31 Specification private Card[] deck container for the cards left in the deck newCard(): Card return a card from the deck ; if the deck is empty, return null moreCards(): boolean return true if more cards remain in the deck; return false, otherwise Methods Attributes class CardDeck models a deck of cards private String suit the card's suit, e.g., spades, hearts, diamonds, clubs Attributes class Card models a playing card private int count the card's count, e.g., ace, 2, 3,..., king

32 Implementation class Card (Figure 8.9) class CardDeck (Figure 9.10)

33 static final variable The keyword, final, states that the variable name can not be changed by an assignment; the value is forever constant. The keyword, static, ensures that these variables are unique and not copied as fields into any Card objects that are constructed from class Card. It is traditional to declare static final variables with names that are all upper-case letters.

34 Two-Dimensional Arrays Definition: A two-dimensional array is an array whose elements are arrays. Example: Election int[][] election = new int[3][4]; the length of row : election.length the length of column : election[0].length Candidate Region int[][] election == a1:int[3][] a1 a2 a3 a a2:int[4] a3:int[4] a4:int[4]

35 int[ ][ ] election = new int[3][4]; election[1][3] = election[1][3] + 1; for ( int j = 0; j != 4; j = j+1 ) { int votes = 0; for ( int i = 0; i != 3; i = i+1 ) { votes = votes + election[i][j]; } System.out.println("Candidate " + j + " has “ + votes + " votes"); } for ( int i = 0; i != 3; i = i+1 ) { int total = 0; for ( int j = 0; j != 4; j = j+1 ) { total = total + election[i][j]; } System.out.println(total + " votes were cast in Region " + i); } for ( int i = 0; i != 3; i = i+1 ) { int[] region = election[i]; // region holds the address of a row int total = 0; for ( int j = 0; j != 4; j = j+1 ) { total = total + region[j]; } System.out.println(total + " votes were cast in Region " + i); } Note: we cannot treat a matrix's columns in a similar way.

36 Ragged Array A two-dimensional array can have rows of different lengths Example: int max_words = 20; char[][] word = new char[max_words][]; int count = 0; // how many words are saved in the array boolean processing = true; while ( processing ) { String s = JOptionPane.showInputDialog("Please type a word: "); if ( s.equals("") ) { processing = false; } else { word[count] = new char[ s.length() ]; for ( int i = 0; i != s.length(); i = i+1 ) // first i-1 characters in s are copied into word[line_num] { word[count][i] = s.charAt(i); } count = count + 1; }

37 a1 : char[20][] null 0000 a2 : char[5] null a1 : char[20][] a2 null 0 char[][] word = new char[max_words][] word[line_num] = new char[s.length()]

38 store “bread” into the array ‘b’‘r’‘e’‘a’ a2 : char[5] a1 : char[20][] a2 null ‘d’ store “is” into the array ‘b’‘r’‘e’‘a’ a2 : char[5] a1 : char[20][] a2 a3 null ‘d’ ‘i’‘s’ a3 : char[2] 0 1

39 Case Study: Slide-Puzzle Game 1 * SlidePuzzleBoard PuzzlePieces private PuzzlePiece[][] board move(int w): boolean private int face_value

40 Class Diagram PuzzleController JOptionPane PuzzleWriter PuzzlePieceSlidePuzzleBoard play() private PuzzlePiece[][] board move(int w): boolean private int face_value displayPuzzle() printError(String s) 1*

41 Implementation class PuzzlePiece (Figure 8.12) class SlidePuzzleBoard (Figure 8.13) class PuzzleController (Figure 8.15) class PuzzleWriter (Figure 8.16) class SlidePuzzle (Figure 8.15)