Microsoft Word - EEL2 Lab5 예외처리와 스레드.docx

Similar documents
PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

Design Issues

JAVA PROGRAMMING 실습 09. 예외처리

ch09

PowerPoint 프레젠테이션

05-class.key

PowerPoint Presentation

슬라이드 1

Microsoft PowerPoint - Java7.pptx

(Microsoft PowerPoint - java1-lecture11.ppt [\310\243\310\257 \270\360\265\345])

JAVA 프로그래밍실습 실습 1) 실습목표 - 메소드개념이해하기 - 매개변수이해하기 - 새메소드만들기 - Math 클래스의기존메소드이용하기 ( ) 문제 - 직사각형모양의땅이있다. 이땅의둘레, 면적과대각

02 C h a p t e r Java

5장.key

Cluster management software

JAVA PROGRAMMING 실습 08.다형성

No Slide Title

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

PowerPoint 프레젠테이션

제11장 프로세스와 쓰레드

Microsoft PowerPoint - Lect04.pptx

Microsoft Word - EEL2 Lab4.docx

비긴쿡-자바 00앞부속

12-file.key

07 자바의 다양한 클래스.key

rmi_박준용_final.PDF

자바 프로그래밍

교육자료

예제 2) Test.java class A intvar= 10; void method() class B extends A intvar= 20; 1"); void method() 2"); void method1() public class Test 3"); args) A

PowerPoint 프레젠테이션

Spring Boot/JDBC JdbcTemplate/CRUD 예제

PowerPoint Presentation

gnu-lee-oop-kor-lec06-3-chap7

Java ...

Microsoft PowerPoint - 2강

C++ Programming

PowerPoint Presentation

Microsoft PowerPoint - 04-UDP Programming.ppt

q 이장에서다룰내용 1 객체지향프로그래밍의이해 2 객체지향언어 : 자바 2

PowerPoint Presentation

1

untitled

09-interface.key

PowerPoint Presentation

Contents Contents 2 1 Abstract 3 2 Infer Checkers Eradicate Infer....

쉽게 풀어쓴 C 프로그래밍

스레드의우선순위 우선순위설정메소드 : void setpriority(int newpriority) newpriority 에설정할수있는등급 : 1( 가장낮은우선순위 ) 부터 10( 가장높은우선순위 ) 가장높은우선순위 : MAX_PRIORITY, 보통우선순위 : NORM_

PowerPoint Presentation

PowerPoint Presentation

Something that can be seen, touched or otherwise sensed

TEST BANK & SOLUTION

01-OOPConcepts(2).PDF

(8) getpi() 함수는정적함수이므로 main() 에서호출할수있다. (9) class Circle private double radius; static final double PI= ; // PI 이름으로 로초기화된정적상수 public

PowerPoint 프레젠테이션

PowerPoint Presentation

JMF3_심빈구.PDF

@OneToOne(cascade = = "addr_id") private Addr addr; public Emp(String ename, Addr addr) { this.ename = ename; this.a

Microsoft PowerPoint - CSharp-10-예외처리

Java Programing Environment

Mobile Service > IAP > Android SDK [ ] IAP SDK TOAST SDK. IAP SDK. Android Studio IDE Android SDK Version (API Level 10). Name Reference V

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Page 2 of 6 Here are the rules for conjugating Whether (or not) and If when using a Descriptive Verb. The only difference here from Action Verbs is wh

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

스레드를적용하지않은결과와스레드를적용한결과의비교 1) 두개의작업을스레드를사용하지않고수행한예 ) : 순차작업 class ThreadTest2 { System.out.print("-");// 화면에 - 를출력하는작업 System.out.print(" ");// 화면에 를출력

step 1-1

목차 BUG DEQUEUE 의 WAIT TIME 이 1 초미만인경우, 설정한시간만큼대기하지않는문제가있습니다... 3 BUG [qp-select-pvo] group by 표현식에있는컬럼을참조하는집합연산이존재하지않으면결괏값오류가발생할수있습니다... 4

No Slide Title

PowerPoint Presentation

fundamentalOfCommandPattern_calmglow_pattern_jstorm_1.0_f…

파일로입출력하기II - 파일출력클래스중에는데이터를일정한형태로출력하는기능을가지고있다. - PrintWriter와 PrintStream을사용해서원하는형태로출력할수있다. - PrintStream은구버전으로가능하면 PrintWriter 클래스를사용한다. PrintWriter

JUNIT 실습및발표

Page 2 of 5 아니다 means to not be, and is therefore the opposite of 이다. While English simply turns words like to be or to exist negative by adding not,

[ 프로젝트이름 ] : Project_Car [ 프로젝트를만든목적 ] : 임의의자동차판매소가있다고가정하고, 고객이원하는자동차의각부분을 Java 를이용하여객 체로생성하고, 그것을제어하는메소드를이용하여자동차객체를생성하는것이목표이다. [ 프로젝트패키지와클래스의내용설명 ] [

JAVA PROGRAMMING 실습 02. 표준 입출력

Java ~ Java program: main() class class» public static void main(string args[])» First.java (main class ) /* The first simple program */ public class

Semantic Consistency in Information Exchange

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Interstage5 SOAP서비스 설정 가이드

Hi-MO 애프터케어 시스템 편 5. 오비맥주 카스 카스 후레쉬 테이블 맥주는 천연식품이다 편 처음 스타일 그대로, 부탁 케어~ Hi-MO 애프터케어 시스템 지속적인 모발 관리로 끝까지 스타일이 유지되도록 독보적이다! 근데 그거 아세요? 맥주도 인공첨가물이

Spring Data JPA Many To Many 양방향 관계 예제

Microsoft PowerPoint - 03-TCP Programming.ppt

쉽게 풀어쓴 C 프로그래밍

ilist.add(new Integer(1))과 같이 사용하지 않고 ilist.add(1)과 같이 사용한 것은 자바 5.0에 추가된 기본 자료형과 해당 객체 자료 형과의 오토박싱/언박싱 기능을 사용한 것으로 오토박싱이란 자바 컴파일러가 객체를 요구하는 곳에 기본 자료형

mytalk

JAVA PROGRAMMING 실습 05. 객체의 활용

목차 INDEX JSON? - JSON 개요 - JSONObject - JSONArray 서울시공공데이터 API 살펴보기 - 요청인자살펴보기 - Result Code - 출력값 HttpClient - HttpHelper 클래스작성 - JSONParser 클래스작성 공공

11¹Ú´ö±Ô

Chap12

신림프로그래머_클린코드.key

DocsPin_Korean.pages

JMF2_심빈구.PDF

C# Programming Guide - Types

슬라이드 1

PowerPoint Template

MasoJava4_Dongbin.PDF

PowerPoint Presentation

PowerPoint Presentation

No Slide Title

4장.문장

Transcription:

EEL2 LAB Week 5: 상속 ( 보충 ), 예외처리와스레드 1 Consider using the following Card class public class Card private String name; public Card() name = ""; public Card(String n) name = n; public String getname() return name; public boolean isexpired() return false; public String format() return "Card holder: " + name; Use this class as a superclass to implement a hierarchy of related classes: (DriverLicense is a sub-class of IDCard) Class IDCard CallingCard DriverLicense Data ID number Card number, PIN Expiration year Write declarations for each of the subclasses For each subclass, supply private instance variables Leave the bodies of the constructors and the format methods blank for now 2 Implement constructors for each of the three subclasses Each constructor should call the superclass constructor to set the name Here is one example: public IDCard(String n, String id) super(n); idnumber = id; 3 Replace the implementation of the format method for the three subclasses The methods should produce a formatted description of the card details The subclass methods should call the superclass format method to get the formatted name of the cardholder 4 Devise another class, Billfold, which contains slots for two cards, card1 and card2, a method void addcard(card) and a method String formatcards() The addcard method checks whether card1 is null If so, it sets card1 to the new card If not, it checks card2 If both cards are set already, the method has no effect Of course, formatcards invokes the format method on each non-null card and produces a string with the format

[card1 card2] What is your Billfold class? 5 Write a tester program that adds two objects of different subclasses of Card to a Billfold object Test the results of the formatcards methods What is the code for your BillfoldTester class? 6 The Card superclass defines a method isexpired, which always returns false This method was overridden in DriverLicense with an identical body, but the method is not appropriate for the driver license Supply a method body for DriverLicenseisExpired() that checks whether the driver license is already expired (ie, the expiration year is less than the current year) To work with dates, you can use the methods and constants supplied in abstract class Calendar which are inherited by the concrete class GregorianCalendar You create a Calendar as follows: GregorianCalendar calendar = new GregorianCalendar(); Then, you can obtain the current year using the constant CalendarYEAR and method get in GregorianCalendar The constant indicates that the method should return the current year By comparing the returned value with the expyear field in DriverLicense, you can determine if the card is expired The code below will retrieve the current year calendarget(calendaryear) 7 The ID card and the phone card don't expire What should you do to reflect this fact in your implementation? 8 Add a method getexpiredcardcount, which counts the number of expired cards in the billfold, to the Billfold class 9 Write a BillfoldTester class that populates a billfold with a phone card and an expired driver license Then call the getexpiredcardcount method Run your tester to verify that your method works correctly What is your tester class? 10 Implement tostring methods for the Card class and its three subclasses The methods should print: the name of the class the values of all instance variables (including inherited instance variables) Typical formats are: Card[name=Edsger W Dijkstra] CallingCard[name=Bjarne Stroustrup][number=4156646425,pin=2234]

Write the code for your tostring methods 11 Implement equals methods for the Card class and its three subclasses Cards are the same if the objects belong to the same class, and if the names and other information (such as the expiration year for driver licenses) match Give the code for your equals methods 12 Change the Card class and give protected access to name Would that change simplify the tostring method of the CallingCard class? How? Is this change advisable? 13 The BankAccount class has three methods with preconditions: 1) The constructor method (initial balance must not be negative) 2) The withdraw method (withdrawal amount must not be greater than the balance) 3) The deposit method (deposit amount must not be negative) Modify the code for the BankAccount class (shown below ) so that each of the three methods throws an IllegalArgumentException if the precondition is violated What is the code for your modified BankAccount class? 14 Using the following BankAccountDemo program, test the code in #13 and show the results import javautilscanner; public class BankAccountDemo public static void main(string[] args) Scanner in = new Scanner(Systemin); Systemoutprint("Initial balance: "); double initialbalance = innextdouble(); Systemoutprint("Amount to deposit: "); double amounttodeposit = innextdouble(); Systemoutprint("Amount to withdraw: "); double amounttowithdraw = innextdouble(); BankAccount account = new BankAccount(initialBalance); accountdeposit(amounttodeposit); accountwithdraw(amounttowithdraw); Systemoutprintln("New balance: " + accountgetbalance());

A bank account has a balance that can be changed by deposits and withdrawals public class BankAccount private double balance; Constructs a bank account with a zero balance public BankAccount() balance = 0; Constructs a bank account with a given balance @param initialbalance the initial balance public BankAccount(double initialbalance) balance = initialbalance; Deposits money into the bank account @param amount the amount to deposit public void deposit(double amount) balance = balance + amount; Withdraws money from the bank account @param amount the amount to withdraw public void withdraw(double amount) balance = balance - amount; Gets the current balance of the bank account @return the current balance public double getbalance() return balance; 15 What happens when you make the following errors with your revised BankAccount class? 1) Construct an account with a negative balance 2) Withdraw more money than the account balance 3) Enter an illegal input (such as "ten" instead of "10") 16 다음조건을만족하는클래스를구현하여테스트하는프로그램을작성 표준입력으로두개의정수를입력받아곱셈연산결과를출력

표준입력에서정수가아닌값이입력되면예외가발생하여실행이중단되는데, 이를예외 처리하여실행되도록 다음소스를참고 int x = 0, y = 0, z = 0; Scanner input = new Scanner(Systemin); Systemoutprintln(" 정수두개입력 : "); x = inputnextint(); y = inputnextint(); z = x * y; Systemoutprintf("%d * %d = %d %n", x, y, z); < 골격프로그램 > import javautilinputmismatchexception; import javautilscanner; public class Ex01 public static void main(string[] args) int x = 0, y = 0, z = 0; Scanner input = new Scanner(Systemin); Systemoutprintln(" 정수두개입력 : "); Systemoutprintf("%d / %d = %d %n", x, y, z); 17 다음조건을만족하도록클래스 BankAccount와이를테스트하는클래스 Ex02 프로그램을작성 새로운예외 InvalidWithdraw 를다음과같이구현 class InvalidWithdraw extends Exception private static final long serialversionuid = 1L; public InvalidWithdraw(String msg) super(msg); 클래스 BankAccount 는최저잔금을저장할수있는필드를지정하는생성자를제공하며, 메소드 deposit(momey) 은입금메소드이며, 메소드 withdraw(momey) 는출금메소드로인출요청금액이음수이거나최저잔금이하로인출을요청하면적당한메시지의예외 InvalidWithdraw 를발생시킨다 즉다음은최저잔고가 -100,000 원인은행계좌를만들어 500,000 원을인출하려는소스로서, 클래스 Ex02 의 main() 에서다음소스의예외처리를작성

BankAccount ba = new BankAccount( 100000); bawithdraw(500000); < 골격프로그램 > class InvalidWithdraw extends Exception class BankAccount int balance = 0; int diff = 0; int min; public BankAccount(int min) thismin = min; public void withdraw(int money) throws InvalidWithdraw public void deposit(int money) public class Ex02 public static void main(string args[]) BankAccount ba = new BankAccount( 100000); try bawithdraw(5000000); catch (InvalidWithdraw e) eprintstacktrace(); 18 위에서구현한클래스 InvalidWithdraw와 BankAccount를다음조건을만족하도록다시구현하여클래스 ex03에서테스트 클래스 Ex03 에서다음소스에문법오류가없도록예외 InvalidWithdraw 를비체크예외로 작성 public class Ex03 public static void main(string args[]) BankAccount ba = new BankAccount( 100000); badeposit(100000); bawithdraw(100000); bawithdraw(200000);

위클래스 Ex03 를실행하면다음과같이마지막문장에서예외가발생하도록 BankAccount 를 적절히구현 ( 단패키지와예외발생줄번호는달라도상관없음 ) 정상입금처리 : 입금금액 =100000, 잔금 =100000 정상출금처리 : 인출금액 =100000, 잔금 = 0 Exception in thread "main" ex03invalidwithdraw: 초과출금요구예외 at ex03bankaccountwithdraw(ex03java:24) at ex03ex03main(ex03java:45) 위클래스 Ex03 에서다시예외처리를구현 19 클래스 PrintTime 은인터페이스 Runnable 을구현하는클래스로지정된생성자의횟수만큼현재 시간과스레드이름을출력하는프로그램으로다음조건을만족하도록스레드 PrintTime 프로그램을 작성하여클래스 Ex04 의 main() 메소드에서테스트 클래스 Ex04 의 main() 메소드에서다음을실행하면다음과같이출력 PrintTime p1 = new PrintTime(3); Thread th1 = new Thread(p1, " 안녕하세요!"); th1setpriority(threadmax_priority 1); th1start(); PrintTime p2 = new PrintTime(6); Thread th2 = new Thread(p2, " 반갑습니다 "); th2setpriority(threadnorm_priority 1); th2start(); 순위 : 4 Sat Jul 07 20:28:56 KST 2012 반갑습니다 순위 : 9 Sat Jul 07 20:28:56 KST 2012 안녕하세요! 순위 : 9 Sat Jul 07 20:28:57 KST 2012 안녕하세요! 순위 : 4 Sat Jul 07 20:28:57 KST 2012 반갑습니다 순위 : 4 Sat Jul 07 20:28:57 KST 2012 반갑습니다 순위 : 9 Sat Jul 07 20:28:57 KST 2012 안녕하세요! 순위 : 4 Sat Jul 07 20:28:58 KST 2012 반갑습니다 순위 : 4 Sat Jul 07 20:28:58 KST 2012 반갑습니다 순위 : 4 Sat Jul 07 20:28:59 KST 2012 반갑습니다 < 골격프로그램 > import javautildate; class PrintTime implements Runnable

public class Ex04 public static void main(string[] args) PrintTime p1 = new PrintTime(3); Thread th1 = new Thread(p1, " 안녕하세요!"); th1setpriority(threadmax_priority 1); th1start(); PrintTime p2 = new PrintTime(6); Thread th2 = new Thread(p2, " 반갑습니다 "); th2setpriority(threadnorm_priority 1); th2start();