명품 자바 프로그래밍 5장 실습문제
1. 다음 main()메소드와 실행 결과를 참고하여 TV를 상속받은 ColorTV클래스를 작성하라.
package ch5;
class TV {
private int size;
public TV(int size) {
this.size = size;
}
protected int getSize() {
return size;
}
}
class ColorTV extends TV {
int colors;
public ColorTV(int size, int colors) {
super(size); // 입력받은 매개변수 중 size는 슈퍼클래스의 생성자에 대입됨.
this.colors = colors; // colors는 ColorTV에서 새로 만들어진 멤버colors에 대입.
}
void printProperty() {
System.out.println(getSize() + "인치 " + colors + "컬러");
}
}
public class problem1 {
public static void main(String[] args) {
ColorTV myTV = new ColorTV(32, 1024);
myTV.printProperty();
}
}
2. 다음 main()메소드와 실행 결과를 참고하여 문제 1의 ColorTV를 상속받는 IPTV 클래스를 작성하라.
package ch5;
class TV {
private int size;
public TV(int size) {
this.size = size;
}
protected int getSize() {
return size;
}
}
class ColorTV extends TV {
int colors;
public ColorTV(int size, int colors) {
super(size); // 입력받은 매개변수 중 size는 슈퍼클래스의 생성자에 대입됨.
this.colors = colors; // colors는 ColorTV에서 새로 만들어진 멤버colors에 대입.
}
void printProperty() {
System.out.println(getSize() + "인치 " + colors + "컬러");
}
}
class IPTV extends ColorTV {
String ip;
public IPTV(String ip, int size, int colors) {
super(size,colors);
this.ip = ip;
}
void printProperty() {
System.out.println("나의 IPTV는 " + ip + " 주소의 " + getSize() + "인치 " + colors + "컬러");
}
}
public class problem2 {
public static void main(String[] args) {
IPTV iptv = new IPTV("192.1.1.2", 32, 2048);
iptv.printProperty();
}
}
3.
package ch5;
import java.util.Scanner;
abstract class Converter { // 단위를 환산하는 추상 클래스
abstract protected double convert(double src); // 추상 메소드1
abstract protected String getSrcString(); // 추상 메소드2
abstract protected String getDestString(); // 추상 메소드3
protected double ratio; // 비율
public void run() {
Scanner s = new Scanner(System.in);
System.out.println(getSrcString() + "을 " + getDestString() + "로 바꿉니다.");
System.out.print(getSrcString() + "을 입력하세요>> ");
double val = s.nextDouble();
double res = convert(val);
System.out.println("변환 결과: " + res + getDestString() + "입니다.");
s.close();
}
}
class Won2Dollar extends Converter {
protected double ratio;
public Won2Dollar(double ratio) { // 생성자
this.ratio = ratio;
}
protected double convert(double src) { // 추상 메소드였던 것1
return src/ratio;
}
protected String getSrcString() { // 추상 메소드였던 것2
return "원";
}
protected String getDestString() { // 추상 메소드였던 것3
return "달러";
}
}
public class problem3 {
public static void main(String[] args) {
Won2Dollar toDollar = new Won2Dollar(1200);
toDollar.run();
}
}
4. Converter클래스를 상속받아 KM을 mile로 변환하는 Km2Mile클래스를 작성하라.
package ch5;
import java.util.Scanner;
abstract class Converter { // 단위를 환산하는 추상 클래스
abstract protected double convert(double src); // 추상 메소드1
abstract protected String getSrcString(); // 추상 메소드2
abstract protected String getDestString(); // 추상 메소드3
protected double ratio; // 비율
public void run() {
Scanner s = new Scanner(System.in);
System.out.println(getSrcString() + "을 " + getDestString() + "로 바꿉니다.");
System.out.print(getSrcString() + "을 입력하세요>> ");
double val = s.nextDouble();
double res = convert(val);
System.out.println("변환 결과: " + res + getDestString() + "입니다.");
s.close();
}
}
class Km2Mile extends Converter {
protected double ratio;
public Km2Mile(double ratio) { // 생성자
this.ratio = ratio;
}
protected double convert(double src) { // 추상 메소드였던 것1
return src/ratio;
}
protected String getSrcString() { // 추상 메소드였던 것2
return "Km";
}
protected String getDestString() { // 추상 메소드였던 것3
return "mile";
}
}
public class problem4 {
public static void main(String[] args) {
Km2Mile toMile = new Km2Mile(1.6);
toMile.run();
}
}
5. Point를 상속받아 색을 가진 점을 나타내는 ColorPoint클래스를 작성하라. 다음 main()메소드를 포함하고 실행 결과와 같이 출력되게 하라.
package ch5;
import java.util.Scanner;
class Point {
private int x,y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
protected void move(int x, int y) {
this.x = x;
this.y = y;
}
}
class ColorPoint extends Point {
public String color;
public ColorPoint (int x, int y, String color) {
super(x,y);
this.color = color;
}
void setXY(int x, int y) {
move(x,y);
}
void setColor(String color) {
this.color = color;
}
public String toString() {
return color + "색의 (" + getX() + "," + getY() + ")의 점";
}
}
public class problem5 {
public static void main(String[] args) {
ColorPoint cp = new ColorPoint(5, 5, "YELLOW");
cp.setXY(10, 20);
cp.setColor("RED");
String str = cp.toString();
System.out.println(str + "입니다.");
}
}
6. Point를 상속받아 색을 가진 점을 나타내는 ColorPoint클래스를 작성하라2.
package ch5;
import java.util.Scanner;
class Point {
private int x,y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
protected void move(int x, int y) {
this.x = x;
this.y = y;
}
}
class ColorPoint extends Point {
public String color;
public ColorPoint () {
super(0,0);
this.color = "BLACK";
}
public ColorPoint (int x, int y) {
super(x,y);
this.color = "BLACK";
}
void setXY(int x, int y) {
move(x,y);
}
void setColor(String color) {
this.color = color;
}
public String toString() {
return color + "색의 (" + getX() + "," + getY() + ")의 점";
}
}
public class problem6 {
public static void main(String[] args) {
ColorPoint zeroPoint = new ColorPoint(); // (0,0)위치의 BLACK색의 점
System.out.println(zeroPoint.toString() + "입니다.");
ColorPoint cp = new ColorPoint(10, 10); // (10,10)위치의 BLACK색의 점
cp.setXY(5, 5);
cp.setColor("RED");
System.out.println(cp.toString() + "입니다.");
}
}
7. Point를 상속받아 3차원의 점을 나타내는 Point3D클래스를 작성하라.
package ch5;
class Point {
private int x,y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
protected void move(int x, int y) {
this.x = x;
this.y = y;
}
}
class Point3D extends Point {
public int z;
public Point3D(int x, int y, int z) { // 서브클래스 Point3D의 생성자
super(x,y); // 슈퍼클래스인 Point의 생성자에 x,y를 대입
this.z = z;
}
void move(int x, int y, int z) {
super.move(x, y); // 슈퍼클래스Point의 move()메소드 사용
this.z = z;
}
void moveUp() { z++; }
void moveDown() { z--; }
public String toString() { // "(x,y,z)의 점" 리턴
return "(" + getX() + "," + getY() + "," + z +")의 점";
}
}
public class problem7 {
public static void main(String[] args) {
Point3D p = new Point3D(1,2,3); // (0,0)위치의 BLACK색의 점
System.out.println(p.toString() + "입니다.");
p.moveUp(); // z축으로 위쪽 이동
System.out.println(p.toString() + "입니다.");
p.moveDown(); // z축으로 아래쪽 이동
p.move(10, 10); // x,y축으로 이동
System.out.println(p.toString() + "입니다.");
p.move(100, 200, 300); // x,y,z축으로 이동
System.out.println(p.toString() + "입니다.");
}
}
8. Point를 상속받아 양수의 공간에서만 점을 나타내는 PositivePoint클래스를 작성하라.
package ch5;
class Point {
private int x,y;
public Point(int x, int y) {
this.x = x; this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
protected void move(int x, int y) {
this.x = x; this.y = y;
}
}
class PositivePoint extends Point {
public PositivePoint() { super(0,0); }
public PositivePoint(int x, int y) { // 서브클래스 PositivePoint의 생성자2
super(x,y); // super키워드는 일단 생성자 젤 위에 있어야하므로 여기 배치
if (x<0 || y<0)
super.move(0, 0); // x,y좌표 둘 중 하나라도 음수값을 가지면 0,0으로 강제 이동
}
public void move(int x, int y) {
if (x>=0 && y>=0) // x,y좌표 둘 다 0이상인지 확인
super.move(x, y);
}
public String toString() { // "(x,y)의 점" 리턴
return "(" + getX() + "," + getY() +")의 점";
}
}
public class problem8 {
public static void main(String[] args) {
PositivePoint p = new PositivePoint();
p.move(10, 10);
System.out.println(p.toString() + "입니다.");
p.move(-5, 5);
System.out.println(p.toString() + "입니다.");
PositivePoint p2 = new PositivePoint(-10, -10);
System.out.println(p2.toString() + "입니다.");
}
}
9. 인터페이스부분인데... 이 부분은 이번 중간 시험범위에서 제외되었으므로 일단 스킾
나중에 접할 기회 생기면 그때 빠르게 익히는걸로..
10. PairMap을 상속받는 Dictionary클래스를 구현하고, 이를 다음과 같이 활용하는 Main()메소드를 가진 클래스 DictionaryApp도 작성하라.
package ch5;
// 키와 값을 하나의 아이템으로 저장하고, 검색 수정이 가능한 추상 클래스
abstract class PairMap {
protected String keyArray []; // key들을 저장하는 배열
protected String valueArray []; // value들을 저장하는 배열
abstract String get(String key); // key값을 가진 value리턴, 없으면 null리턴
abstract void put(String key, String value); // key와 value를 쌍으로 저장. 기존에 key가 있으면 값을 value로 수정
abstract String delete(String key); // key값을 가진 아이템(value와 함께) 삭제 및 삭제된 value값 리턴
abstract int length(); // 현재 저장된 아이템 갯수 리턴
}
class Dictionary extends PairMap {
private int size;
public Dictionary(int nums) { // 생성자 (배열생성도 동시에 이뤄짐)
size = nums;
keyArray = new String[size];
valueArray = new String[size];
for (int i = 0; i<size; i++) {
keyArray[i] = "null";
valueArray[i] = "null";
}
}
// 매개변수 key값과 일치하는 값을 keyArray배열에서 찾고, 있을 경우 그에 해당하는 Value를 반환
String get(String key) {
for (int i =0; i<size; i++) {
if (keyArray[i].equals(key))
return valueArray[i];
}
return "null";
}
// key와 value를 사전에 등록하는 메소드
void put(String key, String value) {
for (int i =0; i<size; i++) { // keyArray 0번째 인덱스부터 문자열이 입력되어 있는지 순서대로 확인
if (keyArray[i].equals(key) == true) { // 만약 매개변수key와 keyArray배열의 i번째key가 일치하면
valueArray[i] = value; // i번째 value만 새로 수정함.
break;
}
if (keyArray[i].equals("null") == true) { // 비어있을 경우, key와 value를 i번째 인덱스에 집어넣음
keyArray[i] = key;
valueArray[i] = value;
break;
}
}
}
// keyArray배열 내의 원소들 중 key와 일치하는 값이 있으면
// keyArray와 valueArray에 들어있는 key,value 삭제 후 삭제된 value리턴
String delete(String key) {
int i;
String temp = "";
for (i =0; i<size; i++) {
if (keyArray[i].equals(key) == true) {
keyArray[i] = "null";
temp = valueArray[i];
valueArray[i] = "null";
}
}
return temp;
}
// 배열에 null이 아닌 값의 갯수를 반환
int length() {
int count = 0;
for (int i =0; i<size; i++) {
if (keyArray[i].equals(null) != true)
count++;
}
return count;
}
}
public class problem10 {
public static void main(String[] args) {
Dictionary dic = new Dictionary(10);
dic.put("황기태", "자바");
dic.put("이재문", "파이썬");
dic.put("이재문", "C++"); // 이재문의 값을 C++로 수정
System.out.println("이재문의 값은 " + dic.get("이재문"));
System.out.println("황기태의 값은 " + dic.get("황기태"));
dic.delete("황기태"); // 황기태 아이템 삭제
System.out.println("황기태의 값은 " + dic.get("황기태")); // 삭제된 아이템 접근
}
}
11.
package ch5;
import java.util.*;
// Calc 추상클래스
abstract class Calc {
int a,b;
abstract void setValue(int a, int b);
public abstract int calculate();
}
class Add extends Calc {
void setValue(int a, int b) {
this.a = a; this.b = b;}
public int calculate() {
return a+b;}
}
class Sub extends Calc {
void setValue(int a, int b) {
this.a = a; this.b = b;}
public int calculate() {
return a-b;}
}
class Mul extends Calc {
public void setValue(int a, int b) {
this.a = a; this.b = b;}
public int calculate() {
return a*b;}
}
class Div extends Calc {
public void setValue(int a, int b) {
this.a = a; this.b = b;}
public int calculate() {
return a/b;}
}
public class problem11 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("두 정수와 연산자를 입력하시오>> ");
int a = s.nextInt();
int b = s.nextInt();
String c = s.next();
switch (c) {
case "+":
Add add = new Add();
add.setValue(a, b);
System.out.println(add.calculate());
break;
case "-":
Sub sub = new Sub();
sub.setValue(a, b);
System.out.println(sub.calculate());
break;
case "*":
Mul mul = new Mul();
mul.setValue(a, b);
System.out.println(mul.calculate());
break;
case "/":
Div div = new Div();
div.setValue(a, b);
System.out.println(div.calculate());
break;
}
s.close();
}
}
12. 텍스트로 입출력하는 간단한 그래픽 편집기를 만들어보자.
강의시간에 화장실 잠깐 갔다오는거 아니면 풀집중하는데 284p 링크드리스트 부분 설명 들었던 기억이 제대로 없음..
스킵.. 시험 나오면 그냥 틀리고 말겠습니다
어차피 이따 시험인데 지금 링크드리스트 제대로 이해할 때까지 찾아볼 바에는 1~5장까지 다시 복습하는 걸로 ㅋㅋ;;
13. 인터페이스 부분.
9번과 같은 이유로 스킵.