광대역 컨포멀 배열 안테나를 위한 빔 형성 연구 및 최적 소자 ...ael.snu.ac.kr/paper_file/... · 2016-07-13 · 광대역 컨포멀 배열 안테나를 위한
객체지향프로그래밍 제 5 주 – 실행제어 , 배열
-
Upload
nathan-serrano -
Category
Documents
-
view
36 -
download
4
description
Transcript of 객체지향프로그래밍 제 5 주 – 실행제어 , 배열
강원대학교 1객체지향프로그래밍
객체지향프로그래밍제 5 주 – 실행제어 , 배열
강원대학교 2객체지향프로그래밍
제 5 장 , 6 장 , 7 장
실행제어 , 배열
제 5 주 강의 목표• 프로그램의 실행 제어를 위한 if 문과 반복문을 배운다 .• 배열과 배열리스트의 사용법을 배운다 .
강원대학교 3객체지향프로그래밍
Chapter 6
결정문 (Decisions)
강원대학교 4객체지향프로그래밍
if 문장if (amount <= balance) balance = balance - amount;
if (amount <= balance) balance = balance - amount;else balance = balance - OVERDRAFT_PENALTY;
if (amount <= balance){ double newBalance = balance - amount; balance = newBalance;}else balance = balance - OVERDRAFT_PENALTY;
강원대학교 5객체지향프로그래밍
관계연산자 (Relational Opera-tors)
Java Math Notation Description
> > Greater than
>= ≥ Greater than or equal
< < Less than
<= ≤ Less than or equal
== = Equal
!= ≠ Not equal
a = 5; // Assign 5 to a if (a == 5) . . . // Test whether a equals 5
강원대학교 6객체지향프로그래밍
소수 비교
double r = Math.sqrt(2);double d = r * r -2;if (d == 0) System.out.println("sqrt(2)squared minus 2 is 0");else System.out.println("sqrt(2)squared minus 2 is not 0 but " + d);
sqrt(2)squared minus 2 is not 0 but 4.440892098500626E-16
* Math.sqrt(2) ==1.41421356237309504...
강원대학교 7객체지향프로그래밍
소수 비교
final double EPSILON = 1E-14;if (Math.abs(x - y) <= EPSILON) // x is approximately equal to y
강원대학교 8객체지향프로그래밍
문자열 비교
• Don't use == for strings!
• Use equals method:
Scanner in = new Scanner(System.in);String input = in.next();if (input == "Y") // WRONG!!!
if (input.equals("Y"))
if (input.equalsIgnoreCase("Y"))
“Y”
“Y”
input
강원대학교 9객체지향프로그래밍
문자열 비교
• s.compareTo(t) < 0 • 사전에서 s 가 t 보다 앞에 있다는 의미
– "car“ 가 "cargo" 보다 앞에 있음– 대문자가 소문자보다 앞에 있음
"Hello" comes before "car"
강원대학교 10객체지향프로그래밍
문자열 비교
String name = “Robert”;String nickname = name.substring(0, 3);if (nickname == “Rob”) // ?
“Rob”
“Rob”
nickname
강원대학교 11객체지향프로그래밍
객체 비교• == 연산자 : 같은 객체인가 ? (tests for identity)• equals 메소드 : 같은 내용을 갖는가 ? (for identical
content)
• box1 != box3• box1.equals(box3) • box1 == box2
Rectangle box1 = new Rectangle(5, 10, 20, 30);Rectangle box2 = box1;Rectangle box3 = new Rectangle(5, 10, 20, 30);
강원대학교 12객체지향프로그래밍
null reference
if (middleInitial == null) System.out.println(firstName + " " + lastName);else System.out.println(firstName + " " + middleInitial + ". "
+ lastName);
강원대학교 13객체지향프로그래밍
단정메소드 (Predicate Method)
• 부울 타입 값을 반환하는 메소드를 정의함
• 조건절에 사용함
public boolean isOverdrawn(){ return balance < 0; }
if (harrysChecking.isOverdrawn()) . . .
강원대학교 14객체지향프로그래밍
단정메소드 (Predicate Method)
• Character 클래스의 단정 메소드
• Scanner 클래스의 단정 메소드
isDigitisLetterisUpperCaseisLowerCase
if (Character.isUpperCase(ch))
if (in.hasNextInt()) n = in.nextInt();hasNextInthasNextDouble
강원대학교 15객체지향프로그래밍
논리연산자 (Boolean Opera-tors)
• && and• || or• ! Not
if (0 < amount && amount < 1000) . . .
if (input.equals("S") || input.equals("M")) . . .
if (!input.equals("S")) . . .
강원대학교 16객체지향프로그래밍
부울 타입 변수
private boolean married;
married = input.equals("M");
if (married) . . . else . . .
if (!married) . . .
if (married == true) . . . // Don't
강원대학교 17객체지향프로그래밍
주의할 점
if (0 < amount < 1000) … // 오류 if (0< amount && amount < 1000) …
if (ch == ‘S’ || ‘M’) … // 오류 if (ch == ‘S’ || ch == ‘M’) …
강원대학교 18객체지향프로그래밍
선택적 실행 (Lazy Evaluation)
if (input != null && Integer.parseInt(input) > 0) …
input != null 판단이 false 이면 뒷 조건표현은 계산하지 않음
강원대학교 19객체지향프로그래밍
Chapter 7
반복 (Iteration)
강원대학교 20객체지향프로그래밍
While loops
while (balance < targetBalance){ year++; double interest = balance * rate / 100; balance = balance + interest;}
강원대학교 21객체지향프로그래밍
do Loops
double value;do{ System.out.print("Please enter a positive number: "); value = in.nextDouble();
}while (value <= 0);
boolean done = false;while (!done){ System.out.print("Please enter a positive number: "); value = in.nextDouble(); if (value > 0) done = true;}
위 두 프로그램은 같은 조작임
강원대학교 22객체지향프로그래밍
for Loops
i = 1;
while (i <= n)
{ double interest = balance * rate / 100; balance = balance + interest; i++;
}
for (int i = 1; i <= n; i++){ double interest = balance * rate / 100; balance = balance + interest;}
강원대학교 23객체지향프로그래밍
for Loops
initialization;while (condition){ statement; update; }
for (initialization; condition; update) statement
강원대학교 24객체지향프로그래밍
초계값 (Sentinel Values)
• Sentinel value: 데이터 세트의 끝을 표시하는 값 • 0 이나 -1 같은 숫자보다는 Q 와 같은 문자를 사용하는
것이 좋음
System.out.print("Enter value, Q to quit: ");String input = in.next();if (input.equalsIgnoreCase("Q")) We are done else { double x = Double.parseDouble(input); . . . }
강원대학교 25객체지향프로그래밍
중간에서 완료여부를 판단하는 루프
boolean done = false;while (!done){ Print prompt String input = read input; if (end of input indicated) done = true; else { // Process input } }
강원대학교 26객체지향프로그래밍
Random Numbers and Simula-tions
• Random number generator
• 주사위 (random number between 1 and 6)
Random generator = new Random();int n = generator.nextInt(a); // 0 <= n < adouble x = generator.nextDouble(); // 0 <= x < 1
int d = 1 + generator.nextInt(6);
강원대학교 27객체지향프로그래밍
File Die.java01: import java.util.Random;02: 03: /**04: This class models a die that, when cast, lands on a05: random face.06: */07: public class Die08: {09: /**10: Constructs a die with a given number of sides.11: @param s the number of sides, e.g. 6 for a normal die12: */13: public Die(int s)14: {15: sides = s;16: generator = new Random();17: }18:
강원대학교 28객체지향프로그래밍
File Die.java
19: /**20: Simulates a throw of the die21: @return the face of the die 22: */23: public int cast()24: {25: return 1 + generator.nextInt(sides);26: }27: 28: private Random generator;29: private int sides;30: }
강원대학교 29객체지향프로그래밍
File DieTester.java
01: /**02: This program simulates casting a die ten times.03: */04: public class DieTester05: {06: public static void main(String[] args)07: {08: Die d = new Die(6);09: final int TRIES = 10;10: for (int i = 0; i < TRIES; i++)11: { 12: int n = d.cast();13: System.out.print(n + " ");14: }15: System.out.println();16: }17: }
강원대학교 30객체지향프로그래밍
Chapter 8
배열과 배열리스트(Arrays and Array Lists)
강원대학교 31객체지향프로그래밍
배열double[] data;data = new double[10];
double[] data = new double[10];
강원대학교 32
객체의 배열
BankAccount[] accounts;accounts = new BankAccount[10];
객체지향프로그래밍
강원대학교 33객체지향프로그래밍
배열의 초기값• 배열 타입에 따라 배열이 구성될 때 자동으로
저장되는 초기값이 다름– Numbers: 0 – Boolean: false – Object References: null
강원대학교 34객체지향프로그래밍
배열의 한 원소를 지칭하는 법
data[2] = 29.95;
System.out.println("The value of this data item is " + data[4]);
강원대학교 35객체지향프로그래밍
배열의 크기
• 배열의 크기를 알기 위해서는 length 필드를 읽음– data.length – 배열은 객체로 취급됨 배열은 인스턴스 필드를 가질
수 있음– length 는 메소드가 아니라 배열 객체의 필드이므로
괄호를 붙이지 않음• 인덱스는 0 부터 length - 1 까지
강원대학교 36객체지향프로그래밍
배열 관련 흔한 오류
double[] data = new double[3];data[3] = 29.95; // ERROR: 범위 밖
double[] data; data[1] = 29.95; // 오류 : 배열을 가리키는 reference 만 // 선언하고 배열객체는 만들지 않았음
double[] data = new double[3];data[0] = 1.2;data[1] = 3.4;data[2] = 0.7;
강원대학교 37객체지향프로그래밍
ArrayList 클래스• 배열과 비슷하나 아래와 같은 차이가 있음
– 필요에 따라 자동으로 커지거나 작아짐– ArrayList 클래스는 삽입 (insert), 삭제
(remove) 등의 메소드를 지원함
강원대학교 38객체지향프로그래밍
ArrayList
• ArrayList 클래스는 범용클래스 (generic class) 임• ArrayList<T> 는 T 타입의 객체들을 저장
ArrayList<BankAccount> accounts = new ArrayList<BankAccount>();accounts.add(new BankAccount(1001));accounts.add(new BankAccount(1015));accounts.add(new BankAccount(1022));
• ArrayList 인스턴스의 크기를 지정해 줄 필요가 없음 ( 기본초기용량 = 10)• 필요에 따라 자동으로 크기가 정해짐
강원대학교 39객체지향프로그래밍
배열리스트 내의 객체를 읽는 법• get 메소드 사용 • 인덱스는 0 부터 시작
BankAccount anAccount = accounts.get(2); // gets the third element of the array list
객체를 배열리스트에서 제거하는 것은 아님 !
accounts
anAccount
강원대학교 40객체지향프로그래밍
배열리스트 내의 객체를 읽는 법
• size() 메소드는 배열리스트 내 객체의 수를 반환함
• 인덱스가 범위를 벗어나면 bounds error
int i = accounts.size();anAccount = accounts.get(i); // Error// legal index values are 0. . .i-1
강원대학교 41객체지향프로그래밍
배열리스트에 객체를 넣는 법• set: 기존 값 엎어쓰기
• add: 값 추가하기
BankAccount anAccount = new BankAccount(1729);accounts.set(2, anAccount);
accounts.add(i, a)
boolean add(E o) o 를 리스트 끝에 추가 void add(int index, E element) element 를 index 위치에 삽입 ( 이후 객체들은 뒤로 밀림 )
강원대학교 42객체지향프로그래밍
배열리스트에서 객체를 삭제하는 법
Accounts.remove(i)
강원대학교 43객체지향프로그래밍
래퍼 (Wrappers)
• ArrayList 는 객체만을 저장함• 기본형 데이터는 ArrayList 에 저장할 수 없음• 여덟 가지 각 기본형 데이터에는 그에 대응되는
wrapper 클래스가 있음
강원대학교 44객체지향프로그래밍
Wrappers
강원대학교 45객체지향프로그래밍
Wrapper 인스턴스
강원대학교 46객체지향프로그래밍
자동포장기능 (Auto-boxing)
• 기본 데이터타입과 wrapper 클래스 간 자동 변환
Double d = new Double(29.95); // 기존 방법Double d = 29.95; // auto-boxing
double x = d.doubleValue(); // 기존 방법double x = d; // auto-unboxing
강원대학교 47객체지향프로그래밍
자동포장기능 (Auto-boxing)
① d 의 포장을 벗겨 double 타입으로 만듦 ② 1 을 더함 ③ 결과를 Double 타입 객체로 포장 ④ 레퍼런스를 e 가 포장된 Double 타입
객체를 가리키도록 함
Double d = new Double(3.1);
Double e = d + 1.0;
강원대학교 48객체지향프로그래밍
배열리스트 조작에서의 자동포장• ArrayList 는 객체만을 저장함• 기본형 데이터는 ArrayList 에 저장할 수 없음• 기본형 데이터를 ArrayList 에 넣으려고 하면
auto-boxing 이 일어남
ArrayList<Double> data = new ArrayList<Double>();data.add(29.95); // auto-boxingdouble x = data.get(0); // auto-unboxing
강원대학교 49객체지향프로그래밍
for-each 루프
double[] data = . . .;double sum = 0;for (double e : data) // "for each e in data"{ sum = sum + e; // e 는 data[0], data[1], ...}
double[] data = . . .;double sum = 0;for (int i = 0; i < data.length; i++){ double e = data[i]; sum = sum + e;}
강원대학교 50객체지향프로그래밍
for-each 루프
ArrayList<BankAccount> accounts = . . . ;double sum = 0;for (BankAccount a : accounts){ sum = sum + a.getBalance();}
double sum = 0;for (int i = 0; i < accounts.size(); i++){ BankAccount a = accounts.get(i); sum = sum + a.getBalance();}
강원대학교 51객체지향프로그래밍
간단한 배열 조작 알고리즘
• 일치하는 횟수 세기• 특정값 찾기• 최소값 혹은 최대값 찾기
• 교과서 8.5 절 샘플 코드 참고
강원대학교 52객체지향프로그래밍
2 차원 배열 (Two-Dimensional Ar-rays)
final int ROWS = 3;final int COLUMNS = 3;String[][] board = new String[ROWS][COLUMNS];
board[i][j] = "x";
for (int i = 0; i < ROWS; i++) for (int j = 0; j < COLUMNS; j++) board[i][j] = " ";
강원대학교 53객체지향프로그래밍
배열의 복사 (Copying Arrays)
double[] data = new double[10];// fill array . . .double[] prices = data;
강원대학교 54객체지향프로그래밍
배열의 복사 (Copying Arrays)
double[] prices = (double[]) data.clone();
강원대학교 55객체지향프로그래밍
여러개의 기본 타입 배열 대신 객체의 배열을 사용함
// 이렇게 하지 마시오 !int[] accountNumbers;double[] balances;
•
강원대학교 56객체지향프로그래밍
여러개의 기본 타입 배열 대신 객체의 배열을 사용함
BankAccount[] accounts;