Microsoft Word - java18-1-final-answer.doc

Similar documents
Microsoft Word - java19-1-final-answer.doc

Microsoft Word - java19-1-midterm-answer.doc

JAVA PROGRAMMING 실습 08.다형성

중간고사

gnu-lee-oop-kor-lec10-1-chap10

Microsoft PowerPoint - 04-UDP Programming.ppt

Microsoft PowerPoint - 14주차 강의자료

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

5장.key

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

09-interface.key

<4D F736F F F696E74202D20C1A63138C0E520C0CCBAA5C6AE20C3B3B8AE28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

PowerPoint Presentation

10장.key

PowerPoint 프레젠테이션

Design Issues

PowerPoint Presentation

11장.key

Microsoft PowerPoint - 2강

PowerPoint Presentation

05-class.key

Microsoft PowerPoint - Java7.pptx

PowerPoint Presentation

쉽게 풀어쓴 C 프로그래밍

중간고사

<4D F736F F F696E74202D20C1A63230C0E520BDBAC0AE20C4C4C6F7B3CDC6AE203128B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

PowerPoint Presentation

Microsoft PowerPoint - java1-lab5-ImageProcessorTestOOP.pptx

PowerPoint Presentation

JAVA PROGRAMMING 실습 09. 예외처리

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

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

PowerPoint 프레젠테이션

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

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

Microsoft Word - cg07-midterm.doc

<4D F736F F F696E74202D20C1A63233C0E520B1D7B7A1C7C820C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

슬라이드 1

<4D F736F F F696E74202D20C1A63139C0E520B9E8C4A120B0FCB8AEC0DA28B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

gnu-lee-oop-kor-lec11-1-chap15

PowerPoint Presentation

제11장 프로세스와 쓰레드

JUNIT 실습및발표

제8장 자바 GUI 프로그래밍 II

Spring Boot/JDBC JdbcTemplate/CRUD 예제

ch09

<4D F736F F F696E74202D20C1A63038C0E520C5ACB7A1BDBABFCD20B0B4C3BC4928B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

A Tour of Java IV

PowerPoint Presentation

PowerPoint Presentation

예제 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

JAVA PROGRAMMING 실습 05. 객체의 활용

9장.key

단국대학교멀티미디어공학그래픽스프로그래밍중간고사 (2011 년봄학기 ) 2011 년 4 월 26 일학과학번이름 중간고사 담당교수 : 단국대학교멀티미디어공학전공박경신 l 답은반드시답안지에기술할것. 공간이부족할경우반드시답안지몇쪽의뒤에있다고명기한후기술할것. 그외의경우의답안지뒤

자바GUI실전프로그래밍2_장대원.PDF

02 C h a p t e r Java

강의자료

C# Programming Guide - Types

10.0pt1height.7depth.3width±â10.0pt1height.7depth.3widthÃÊ10.0pt1height.7depth.3widthÅë10.0pt1height.7depth.3width°è10.0pt1height.7depth.3widthÇÁ10.0pt1height.7depth.3width·Î10.0pt1height.7depth.3width±×10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width¹Ö pt1height.7depth.3widthŬ10.0pt1height.7depth.3width·¡10.0pt1height.7depth.3width½º, 10.0pt1height.7depth.3width°´10.0pt1height.7depth.3widthü, 10.0pt1height.7depth.3widthº¯10.0pt1height.7depth.3width¼ö, 10.0pt1height.7depth.3width¸Þ10.0pt1height.7depth.3width¼Ò10.0pt1height.7depth.3widthµå

JAVA PROGRAMMING 실습 02. 표준 입출력

Cluster management software

12-file.key

Microsoft PowerPoint 자바-기본문법(Ch2).pptx

TEST BANK & SOLUTION

쉽게 풀어쓴 C 프로그래밍

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

자바 프로그래밍

Java Programing Environment

JMF3_심빈구.PDF

PowerPoint Presentation

PowerPoint Presentation

rmi_박준용_final.PDF

교육자료

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

PowerPoint Presentation

03-JAVA Syntax(2).PDF

슬라이드 1

PowerPoint Presentation

비긴쿡-자바 00앞부속

Chap12

untitled

PowerPoint Presentation

JAVA PROGRAMMING 실습 05. 객체의 활용

Microsoft PowerPoint - 06-Chapter09-Event.ppt

1

PowerPoint 프레젠테이션

A Tour of Java V

슬라이드 1

PowerPoint Presentation

No Slide Title

JAVA PROGRAMMING 실습 07. 상속

슬라이드 1

class Sale void makelineitem(productspecification* spec, int qty) SalesLineItem* sl = new SalesLineItem(spec, qty); ; 2. 아래의액티비티다이어그램을보고 Java 또는 C ++,

Microsoft PowerPoint - Lect04.pptx

PowerPoint 프레젠테이션

fundamentalOfCommandPattern_calmglow_pattern_jstorm_1.0_f…

Let G = (V, E) be a connected, undirected graph with a real-valued weight function w defined on E. Let A be a set of E, possibly empty, that is includ

A Tour of Java III

Transcription:

기말고사 담당교수 : 단국대학교응용컴퓨터공학박경신 답은반드시답안지에기술할것. 공간이부족할경우반드시답안지몇쪽의뒤에있다고명기한후기술할것. 그외의경우의답안지뒤쪽이나연습지에기술한내용은답안으로인정안함. 답에는반드시네모를쳐서확실히표시할것. 답안지에학과, 학번, 이름외에본인의암호 (4자리숫자 ) 를기입하면성적공고시학번대신암호를사용할것임. 1. 다음 sub1 과 sub2 의실행결과가같도록, sublist 메소드내부의코드를완성하라. (10 점 ) public static int[] sublist(int[] list, int fromindex, int toindex) { int size = toindex fromindex; int[] result = new int[size]; for (int i = 0; i < size; i++) { result[i] = list[fromindex + i]; return result; public static List<Integer> sublist(list<integer> list, int fromindex, int toindex) { List<Integer> result = new ArrayList<Integer>(); for (int i = fromindex; i < toindex; i++) { result.add(list.get(i)); return result; public static void main(string[] args) { int[] dataarray = {7, 5, 8, 5, 9, 7, 2, 3; int[] sub1 = sublist(dataarray, 2, 5); System.out.println("sub1 = " + Arrays.toString(sub1)); // sub1 = [8, 5, 9] List<Integer> datalist = Arrays.asList(7, 5, 8, 5, 9, 7, 2, 3); List<Integer> sub2 = sublist(datalist, 2, 5); System.out.println("sub2 = " + Arrays.toString(sub2.toArray())); // sub2 = [8, 5, 9] 1/9

2. 다음코드의실행결과를적어라 (parameter passing 에유의할것 ). (10 점 ) public static int mystery(int n, int[] numbers) { n += 100; numbers[2] ; System.out.println(n + " " + Arrays.toString(numbers)); return numbers[1] * 2; public static void mystery(int[] x, int[] y) { int[] t = x; x = y; y = t; System.out.println(Arrays.toString(x) + " " + Arrays.toString(y)); public static void mystery(int[] list) { for (int i = 1; i < list.length 1; i++) { if (list[i] <= list[i + 1]) { list[i + 1] = i * 2; public static void main(string[] args) { int a = 4; int b = 8; int[] data = {5, 10, 15; a = mystery(b, data); // 108 [5, 10, 14] System.out.println(a + " " + b + " " + Arrays.toString(data)); // 20 8 [5, 10, 14] System.out.println(); int[] x = {1, 2; int[] y = {3, 4, 5; mystery(x, y); // [3,4,5] [1,2] System.out.println(Arrays.toString(x) + " " + Arrays.toString(y)); // [1,2] [3,4,5] System.out.println(); int[] data1 = {4, 1, 3; int[] data2 = {2, 1, 3, 2; int[] data3 = {1, 1, 1, 1, 8; mystery(data1); System.out.println("data1 = " + Arrays.toString(data1)); // data1=[4,1,2] mystery(data2); System.out.println("data2 = " + Arrays.toString(data2)); // data2=[2,1,2,4] mystery(data3); System.out.println("data3 = " + Arrays.toString(data3)); // data3=[1,1,2,1,6] System.out.println(); 108 [5, 10, 14] 20 8 [5, 10, 14] [3, 4, 5] [1,2] // 자바는 pass-by-value 방식이라서, 내부에서는바뀌지만 [1, 2] [3, 4, 5] // 자바는 pass-by-value 방식이라서, 외부에는영향을주지않는다. data1 = [4, 1, 2] data2 = [2, 1, 2, 4] data3 = [1, 1, 2, 1, 6] 2/9

3. 다음은클래스상속관계에서다형성을보여주고있다. 아래의질문에답하라. (30 점 ) interface I { void method1(int v); public abstract class A implements I { public abstract void method2(); public void method3() { System.out.println(this); return "a"; public class D extends A { public void method1(int v) { System.out.println("d1 " + v); public void method2() { System.out.println("d2"); return "d"; public class C extends A { protected int m = 10; public void method1(int v) { System.out.println("c1 " + v); public void method2() { System.out.println("c2 " + m); return "c"; public class B extends C { protected int m = 20; public void method2() { System.out.println("b2 " + this.m + " " + super.m); // (3.3) return "b"; public class E extends C { public void method2() { System.out.println("e2 " + this.m + " " + super.m); // (3.3) 3.1 interface 와 abstract class 가무엇인지간단히설명하라. (5 점 ) 인터페이스는클래스에서구현해야하는동작을지정하는데사용하는추상형. 자바에서인터페이스는다중상속이가능하다. 추상클래스는여러기존의클래스에서공통된부분을추상화한것. 추상클래스를상속하는클래스에게그구현을강제화하는클래스. 하나이상의추상메소드를포함하는클래스이다. 3/9

3.2 abstract method 가무엇인지간단히설명하라. 위의코드에서예를찾아서보여라. (5 점 ) 추상메소드는메소드만선언해놓고구현내용은없는것으로, 추상메소드를상속받은클래스는반드시추상메소드를 override 해서구현해야한다. 위의코드에서는 method1 과 method2 가추상메소드이다. 3.3 클래스 B 와 E 의 method2() 에 this.m 과 super.m 의값을말하고자세히설명하라. (5 점 ) 클래스 B 의 method2() 에서사용되는 this.m 은클래스 B 에서다시정의한멤버 m 으로 20, super.m 은클래스 C 의멤버 m 으로 10 이다. 따라서 b2 20 10 클래스 E 의 method2() 에서사용되는 this.m 과 super.m 은클래스 C 의멤버 m 이므로모두 10 이다. 따라서 e2 10 10 3.4 다음코드의실행결과를적고, 코드에 upcasting 과 downcasting 을표시하라. (5 점 ) A a = new B(); // upcasting System.out.println(a); // dynamic binding A.toString() => B.toString() b B b = new B(); Object o = b; // upcasting ((B)o).method2(); // downcasting B.method2() b2 20 10 System.out.println((B)o); // downcasting, B.toString() b System.out.println((C)o); // downcasting, C.toString() => B.toString() b System.out.println(o); // Object.toString() => B.toString() b System.out.println(); b // B.toString() b2 20 10 // B.method2() b // B.toString() b // C.toString() => B.toString() b // Object.toString() => B.toString() 3.5 다음코드의실행결과를적고이유를자세히설명하라 (dynamic binding 에주의 ). (10 점 ) A[] elements = {new C(), new D(), new E(); for (int i = 0; i < elements.length; i++) { System.out.println(elements[i]); elements[i].method1(i); elements[i].method2(); elements[i].method3(); c // A.toString() => C.toString() c1 0 // A.method1(0) => C.method1(0) c2 10 // A.method2() => C.method2() c // A.method3() 호출하는데그내부의 this 는 c d // A.toString() => D.toString() d1 1 // A.method1(1) => D.method1(1) d2 // A.method2() => D.method2() d // A.method3() 호출하는데그내부의 this 는 d c // A.toString() => E.toString() 없으므로 C.toString() 호출 c1 2 // A.method1(2) => E.method1(2) 없으므로 C.method1(2) 호출 e2 10 10 // A.method2() => E.method2() c // A.method3() 호출하는데그내부의 this 는 e, 하지만 E.toString() 이없으므로 C.toString() 호출 4/9

4. 다음은 Value 와 TripleValue 클래스이다. Collection 관련질문에답하라. (30 점 ) import java.util.*; public class Value implements Comparable<Value> { private int x; private int y; public Value() { this(0, 0); public Value(int x, int y) { set(x, y); public void set(int x, int y) { this.x = x; this.y = y; public int getx() { return x; public int gety() { return y; return x + "," + y; public boolean equals(object other) { if (this == other) return true; if (other instanceof Value) { Value that = (Value) other; return x == that.x && y == that.y; return false; public int hashcode() { return Objects.hash(x, y); public int compareto(value other) { return x other.x; public static Comparator<Value> YComparator = new Comparator<Value>() { public int compare(value v1, Value v2) { return v1.y v2.y; ; import java.util.*; public class TripleValue extends Value { private int z; public TripleValue() { this(0, 0, 0); public TripleValue(int x, int y, int z) { super(x, y); this.z = z; public void set(int x, int y, int z) { super.set(x, y); 5/9

this.z = z; public int getz() { return z; return getx() + "," + gety() + "," + z; public boolean equals(object other) { if (this == other) return true; if (other instanceof TripleValue) { TripleValue that = (TripleValue)other; return getx() == that.getx() && gety() == that.gety() && z == that.z; return false; public int hashcode() { return Objects.hash(getX(), gety(), z); public static Comparator<TripleValue> ZComparator = new Comparator<TripleValue>() { public int compare(triplevalue v1, TripleValue v2) { return v1.z v2.z; ; 4.1 다음코드의실행결과와같도록, values 를사용하여 List<Value> list 를작성하라. (5 점 ) Value[] values = { new Value(1, 2), new Value(1, 2), new TripleValue( 3, 4, 5), new TripleValue( 3, 4, 5), new TripleValue(7, 8, 9) ; for (Value value : values) System.out.println(value); List<Value> list = new ArrayList<Value>(); for (Value value : values) { list.add(value); for (Value value : list) { System.out.println(value); 4.2 위 4.1 의 list 를사용하여, 각각 X, Y 값으로 sort 하는코드를작성하라. (5 점 ) list.sort(null); // 기본 X 값으로 sort. Comparable<Value> 의 compareto 를사용 list.sort(value.ycomparator); // Y 값으로 sort 는 Comparator<Value> 의 compare 사용 // 만약 list 의 element 가 TripleValue 였다면 list.sort(triplevalue.zcomparator) 사용가능 // 또는 Collections.sort(list); // 기본 X 값으로 sort. Comparable<Value> 의 compareto 를사용 Collections.sort(list, Value.YComparator); // Y 값으로 sort 는 Comparator<Value> 의 compare 사용 6/9

4.3 위 4.1 의 values 를사용한 HashMap 코드이다. 다음실행결과를적어라. (5 점 ) Map<Value, Integer> map = new HashMap<Value, Integer>(); for (int i = 0; i < values.length; i++) { map.put(values[i], i+1); for (Map.Entry<Value, Integer> e : map.entryset()) { System.out.println(e.getKey() + " => " + e.getvalue()); map.remove(values[2]); for (Map.Entry<Value, Integer> e : map.entryset()) { System.out.println(e.getKey() + " => " + e.getvalue()); 1, 2 => 2 7, 8, 9 => 5 3, 4, 5 => 4 // remove 후 1, 2 => 2 7, 8, 9 => 5 4.4 위의 4.3 실행결과와같도록, foreach 대신 iterator 와 while 를사용하여동일한코드를작성하라. (5 점 ) Iterator<Value> it = map.keyset().iterator(); while (it.hasnext()) { Value key = it.next(); Integer value = map.get(key); System.out.println(key + " => " + value); 4.5 다음코드의실행결과를적고 == 과 equals 와 hashcode 를자세히설명하라. (10 점 ) TripleValue v1 = new TripleValue(1,2,3); TripleValue v2 = new TripleValue(1,2,3); TripleValue v3 = v1; System.out.println("v1=" + v1); System.out.println("v2=" + v2); System.out.println("v3=" + v3); System.out.println("v1 == v2 " + (v1 == v2)); System.out.println("v1 == v3 " + (v1 == v3)); System.out.println("v1 equals v2 " + v1.equals(v2)); System.out.println("v1 equals v3 " + v1.equals(v3)); System.out.println("v1.hashCode == v2.hashcode " + (v1.hashcode() == v2.hashcode())); System.out.println("v1.hashCode == v3.hashcode " + (v1.hashcode() == v3.hashcode())); v1=1,2,3 v2=1,2,3 v3=1,2,3 v1 == v2 false v1 == v3 true // 레퍼런스가같은 v1 == v3 v1 equals v2 true // 객체의내용이같으므로 (equals 재정의되어있으므로 ) v1 equals v3 true // 객체의내용이같으므로 (equals 재정의되어있으므로 ) v1.hashcode == v2.hashcode true // hashcode 재정의되어있으므로 v1.hashcode == v3.hashcode true // hashcode 재정의되어있으므로 == 연산자는 reference type 의경우, reference 가같은지를비교한다. equals 메소드는두객체의내용이같은지를비교한다. hashcode 메소드는객체의내용으로 hashcode 값을생성한다. 따라서객체의내용이같을경우같은 hashcode 를갖게된다. hashcode 가 override 되어있을경우, HashMap 이나 HashSet 을사용하는 collection 에서동일한 Key 로사용할수없다. 7/9

5. 다음은 TripleCalculatorFrame 클래스이다. 아래빈칸에코드를채워라. (20 점 ) // TripleOperator public enum TripleOperator { MIN, MAX, MEDIAN, MEAN, SUM; public static TripleOperator nameof(int value) { switch (value) { case 0: return MIN; case 1: return MAX; case 2: return MEDIAN; case 3: return MEAN; case 4: return SUM; default: return null; public double calculate(int x, int y, int z) { switch (this) { case MIN: return Math.min(Math.min(x, y), z); case MAX: return Math.max(Math.max(x, y), z); case MEDIAN: return Math.max(Math.min(x,y), Math.min(Math.max(x,y),z)); case MEAN: return (x + y + z) / 3.0; case SUM: return x + y + z; default: throw new AssertionError("Unknown operations " + this); // TripleCalculator public class TripleCalculator { private TripleValue value; // x,y,z value private TripleOperator op; // operator public TripleCalculator() { set(0, 0, 0, TripleOperator.MIN); public void set(int x, int y, int z, TripleOperator op) { this.value = new TripleValue(x, y, z); this.op = op; public double getw() { return op.calculate(value.getx(), value.gety(), value.getz()); // TripleCalculatorFrame import java.awt.event.*; import javax.swing.*; public class TripleCalculatorFrame extends JFrame implements ActionListener, KeyListener { JLabel[] labels = new JLabel[4]; JTextField[] textfields = new JTextField[4]; JRadioButton[] rbuttons = new JRadioButton[5]; String[] names = {"MIN", "MAX", "MEDIAN", "MEAN", "SUM"; ButtonGroup rgroup = new ButtonGroup(); JPanel rpanel = new JPanel(); TripleCalculator calc = new TripleCalculator(); public TripleCalculatorFrame() { super("triplecalculatorframe"); this.setlayout(null); for (int i = 0; i < 3; i++) { labels[i] = new JLabel(" 숫자 " + (i+1)); labels[i].setbounds(10, 10 + 30 * i, 50, 25); textfields[i] = new JTextField("0", 10); textfields[i].setbounds(100, 10 + 30 * i, 200, 25); textfields[i].addkeylistener(this); // event 8/9

this.add(labels[i]); this.add(textfields[i]); for (int i = 0; i < 5; i++) { rbuttons[i] = new JRadioButton(names[i]); rbuttons[i].addactionlistener(this); // event rgroup.add(rbuttons[i]); rpanel.add(rbuttons[i]); rbuttons[0].setselected(true); rpanel.setbounds(10, 100, 300, 25); this.add(rpanel); labels[3] = new JLabel(" 결과 "); labels[3].setbounds(10, 150, 50, 25); textfields[3] = new JTextField(10); textfields[3].setbounds(100, 150, 200, 25); this.add(labels[3]); this.add(textfields[3]); setsize(350, 250); setresizable(false); setvisible(true); setdefaultcloseoperation(jframe.exit_on_close); private int selectoperator() { for (int i = 0; i < 5; i++) { if (rbuttons[i].isselected()) { return i; return 0; private void calculate(int index) { int x = Integer.parseInt(textfields[0].getText()); int y = Integer.parseInt(textfields[1].getText()); int z = Integer.parseInt(textfields[2].getText()); TripleOperator op = TripleOperator.nameOf(index); calc.set(x, y, z, op); labels[3].settext(names[index]); textfields[3].settext("" + calc.getw()); public void actionperformed(actionevent e) { JRadioButton rbutton = (JRadioButton) e.getsource(); for (int i = 0; i < 5; i++) { if (rbutton == rbuttons[i]) { calculate(i); // 계산 public void keytyped(keyevent e) { public void keyreleased(keyevent e) { public void keypressed(keyevent e) { int key = e.getkeycode(); if (key == KeyEvent.VK_ENTER) { calculate(selectoperator()); // 계산 - 끝 - 9/9