반응형

이전 문제까지는 명품JAVA 개정판이였고 이번 문제부터 개정 4판입니다.

 

문제

Vector<Shape>의 벡터를 이용하여 그래픽 편집기를 만들어보자. 본문 5.6절과 5.7절에서 사례로 든 추상 클래스 Shape과 Line, Rect, Circle 클래스 코드를 잘 완성하고 이를 활용하여 "삽입", "삭제", "모두 보기", "종료"의 4가지 그래픽 편집 기능을 프로그램으로 작성하라. 6장 실습문제 6번을 Vector<Shape>을 이용하여 재작성하는 연습이다. Vector를 이용하면 6장 실습문제 6번보다 훨씬 간단히 작성됨을 경험할 수 있다.

출력 예시

그래픽 에디터 beauty을 실행합니다.
삽입(1), 삭제(2), 모두보기(3), 종료(4) >> 1
Line(1), Rect(2), Circle(3) >> 2
삽입(1), 삭제(2), 모두보기(3), 종료(4)>>1
Line(1), Rect(2), Circle(3) >> 3
삽입(1), 삭제(2), 모두보기(3), 종료(4)>>3
Rect
Circle
삽입(1), 삭제(2), 모두보기(3), 종료(4)>>2
삭제할 도형의 위치 >> 3
삭제할 수 없습니다.
삽입(1), 삭제(2), 모두보기(3), 종료(4)>>4
beauty을 종료합니다.

소스 코드

import java.util.Scanner;
import java.util.Vector;

abstract class Shape{
	public Shape() {};
	public abstract String draw(); 
}
class LineTen extends Shape{
	@Override
	public String draw() {
		return "Line";
	}
}
class RectTen extends Shape{
	@Override
	public String draw() {
		return "Rect";
	}
}
class CircleTen extends Shape{
	@Override
	public String draw() {
		return "Circle";
	}
}

class GraphicEditorbeauty{
	Vector<Shape> v = new Vector<Shape>();
	
	public void Menu() {
		Scanner s = new Scanner(System.in);
		System.out.println("그래픽 에디터 beauty을 실행합니다.");
		while(true) {
		System.out.print("삽입(1), 삭제(2), 모두보기(3), 종료(4)>>");
		int input = s.nextInt();
		switch(input) {
		case 1:
			addshape(s);
			break;
		case 2:
			removeshape(s);
			break;
		case 3:
			Print();
			break;
		case 4:
			System.out.println("beauty을 종료합니다.");
			System.exit(0);
			break;
		default:
			break;
		}
		}
	}
	private void Print() {
		for(int i = 0;i<v.size();i++)
		{
			System.out.println(v.get(i).draw());
		}
	}
	private void addshape(Scanner s) {
		System.out.print("Line(1), Rect(2), Circle(3) >> ");
		int input = s.nextInt();
		switch(input) {
		case 1:
			LineTen L = new LineTen();
			v.add(L);
			break;
		case 2:
			RectTen R = new RectTen();
			v.add(R);
			break;
		case 3:
			CircleTen C = new CircleTen();
			v.add(C);
			break;
		default:
			System.out.println("잘못된 입력");
			break;
		}
	}
	private void removeshape(Scanner s) {
		System.out.println("삭제할 도형의 위치 >> ");
		int remove = s.nextInt();
		if(v.size() <= remove) {
			System.out.println("삭제할 수 없습니다.");
		}
		else
			v.remove(remove);
	}
	
}

public class Main10 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GraphicEditorbeauty GE = new GraphicEditorbeauty();
		GE.Menu();
	}

}
반응형
반응형

문제

다음 AbstractStack은 정수 스택 클래스로서 추상 클래스이다.

class AbstractStack {
public:
	virtual bool push(int n) = 0; //스택에 n을 푸시한다. 스택이 full이면 false 리턴
	virtual bool pop(int& n) = 0; //스택에서 팝한 정수를 n에 저장하고 스택이 empty이면 리턴
	virtual int size() = 0; // 현재 스택에 저장된 개수 리턴
};

이를 상속받아 정수를 푸시, 팝하는 IntStack 클래스를 만들고 사용 사례를 보아라.

 

소스코드

#include<iostream>
using namespace std;

class AbstractStack {
public:
	virtual bool push(int n) = 0; //스택에 n을 푸시한다. 스택이 full이면 false 리턴
	virtual bool pop(int& n) = 0; //스택에서 팝한 정수를 n에 저장하고 스택이 empty이면 리턴

	virtual int size() = 0; // 현재 스택에 저장된 개수 리턴
};

class IntStack : public AbstractStack {
	int* data;
	int s, top;
public:
	IntStack(int s) {
		this->s = s;
		data = new int[s];
		top = -1;
	}
	~IntStack() { delete[] data; }
	void show() {
		for (int i = top; i >= 0; i--)
		{
			cout << data[i] << " ";
		}
		cout << endl;
	}
	virtual bool push(int n) {
		if (top + 1 >= s)return false; //top size보다 같거나 크면 false리턴
		data[++top] = n; //아니라면 값을 넣은 후 true 리턴
		return true;
	}
	virtual bool pop(int& n) {
		if (top <= -1)return false; //top이 -1보다 같거나 작다면 false리턴
		n = data[top--];
		return true;
	}
	virtual int size() {
		return top + 1; //저장된 개수 리턴 0부터 시작하므로 +1
	}
};

int main()
{
	int size, menu, push, pop;

	cout << "스택의 크기는?>> ";
	cin >> size;

	IntStack stack(size);

	while (true) {
		cout << endl << "1. 푸시 2. 팝 3. 스택보기 4. 종료" << endl << "메뉴 선택>> ";
		cin >> menu;
		switch (menu) {
		case 1:
			cout << "push 할 값>> ";
			cin >> push;
			if (stack.push(push))
				cout << "push 완료" << endl;
			else
				cout << "push할 공간이 없습니다." << endl;
			break;
		case 2:
			if (stack.pop(pop))
				cout << "pop 완료 pop한 값 : " << pop << endl;
			else
				cout << "빈 스택입니다." << endl;
			break;
		case 3:
			cout << "스택 데이터 : ";
			stack.show();
			break;
		case 4:
			cout << "종료" << endl;
			exit(1);
		default:
			cout << "잘못 입력" << endl;
			break;
		}
	}
}

 

결과

 

반응형
반응형

문제

디지털 회로에서 기본적인 게이트로 OR 게이트, AND 게이트, XOR 게이트 등이 있다.

이들은 각각 두 입력 신호를 받아 OR 연산, AND 연산, XOR 연산을 수행한 결과를 출력한다. 이 게이트들을 각각 ORGate, XORGate, ANDGate 클래스로 작성하고자 한다. ORGate, XORGate, ANDGate 클래스가 AbstractGate를 상속받도록 작성하라.

class AbstractGate { //추상 클래스
protected:
	bool x, y;
public:
	void set(bool x, bool y) { this->x = x; this->y = y; }
	virtual bool operation() = 0;
};

 

ANDGate, ORGate, XORGate를 활용하는 사례와 결과는 다음과 같다.

int main() {
	ANDGate and;
	ORGate or;
	XORGate xor;

	and.set(true, false);
	or.set(true, false);
	xor.set(true, false);
	cout.setf(ios::boolalpha); //불린 값은 "true", "false" 문자열로 출력할 것을 지시
	cout << and .operation() << endl; // AND 결과는 false
	cout << or.operation() << endl; // OR 결과는 true
	cout << xor .opeartion() << endl; // XOR 결과는 true
}

 

결과

false
true
true

 

소스코드

#include<iostream>
using namespace std;
class AbstractGate { //추상 클래스
protected:
	bool x, y;
public:
	void set(bool x, bool y) { this->x = x; this->y = y; }
	virtual bool operation() = 0;
};

class ANDGate : public AbstractGate {
public:
	virtual bool operation() {
		if (x == true && y == true)
			return true;
		else return false;
	}
};
class ORGate : public AbstractGate {
public:
	virtual bool operation() {
		if (x == true || y == true)
			return true;
		else return false;
	}
};
class XORGate : public AbstractGate {
public:
	virtual bool operation() {
		if (x != y)
			return true;
		else return false;
	}
};

int main() {
	ANDGate And;
	ORGate Or;
	XORGate Xor;

	And.set(true, false);
	Or.set(true, false);
	Xor.set(true, false);
	cout.setf(ios::boolalpha); //불린 값은 "true", "false" 문자열로 출력할 것을 지시
	cout << And.operation() << endl; // AND 결과는 false
	cout << Or.operation() << endl; // OR 결과는 true
	cout << Xor.operation() << endl; // XOR 결과는 true
}

 

반응형
반응형

3~4번에 쓰이는 추상 클래스 LoopAdder 입니다.

class LoopAdder { // 추상 클래스 
	string name; // 루프의 이름 
	int x, y, sum; // x에서 y까지의 합은 sum 
	void read(); // x, y 값을 읽어 들이는 함수 
	void write(); // sum을 출력하는 함수 
protected:
	LoopAdder(string name = "") { // 루프의 이름을 받는다. 초깃값은 "" 
		this->name = name;
	}
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0; // 순수 가상 함수. 루프를 돌며 합을 구하는 함수 
public:
	void run(); // 연산을 진행하는 함수 
};

void LoopAdder::read() { // x, y 입력 
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더한다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}

void LoopAdder::write() { // 결과 sum 출력 
	cout << x << "에서 " << y << "까지의 합 = " << sum << " 입니다" << endl;
}

void LoopAdder::run() {
	read(); // x, y를 읽는다 
	sum = calculate(); // 루프를 돌면서 계산한다. 
	write(); // 결과 sum을 출력한다. 
}

 

문제

LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록 WhileLoopAdder, DowhileLoopAdder 클래스를 작성하라. while 문, do-while 문을 이용하여 합을 구하도록 calculate() 함수를 각각 작성하면 된다.

int main() {
	WhileLoopAdder whileLoop("While Loop");
	DoWhileLoopAdder doWhileLoop("Do While Loop");

	whileLoop.run();
	doWhileLoop.run();
}

 

결과

While Loop :
처음 수에서 두번째 수까지 더합니다.두 수를 입력하세요 >> 3 10
3에서 5까지의 합 = 12 입니다 Do While Loop :
처음 수에서 두번째 수까지 더합니다.두 수를 입력하세요 >> 10 20
10에서 20까지의 합 = 165

 

소스코드

#include<iostream>
using namespace std;
class LoopAdder { // 추상 클래스 
	string name; // 루프의 이름 
	int x, y, sum; // x에서 y까지의 합은 sum 
	void read(); // x, y 값을 읽어드리는 함수 
	void write(); // sum을 출력하는 함수 
protected:
	LoopAdder(string name = "") { // 루프의 이름을 받는다. 초깃값은 "" 
		this->name = name;
	}
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0; // 순수 가상 함수. 루프를 돌며 합을 구하는 함수 
public:
	void run(); // 연산을 진행하는 함수 
};

void LoopAdder::read() { // x, y 입력 
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더한다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}

void LoopAdder::write() { // 결과 sum 출력 
	cout << x << "에서 " << y << "까지의 합 = " << sum << " 입니다" << endl;
}

void LoopAdder::run() {
	read(); // x, y를 읽는다 
	sum = calculate(); // 루프를 돌면서 계산한다. 
	write(); // 결과 sum을 출력한다. 
}
class WhileLoopAdder : public LoopAdder {
	string name;
public:
	WhileLoopAdder(string name = "") :LoopAdder(name) { this->name = name; }
	virtual int calculate() {
		int sum = 0;
		int x = getX();
		int y = getY();
		while (x <= y) {
			sum += x;
			x++;
		}
		return sum;
	}
};

class DoWhileLoopAdder : public LoopAdder {
	string name;
public:
	DoWhileLoopAdder(string name = "") :LoopAdder(name) { this->name = name; }
	virtual int calculate() {
		int sum = 0;
		int x = getX();
		int y = getY();
		do {
			sum += x;
			x++;
		} while (x <= y);
		return sum;
	}
};
int main() {
	WhileLoopAdder whileLoop("While Loop");
	DoWhileLoopAdder doWhileLoop("Do While Loop");

	whileLoop.run();
	doWhileLoop.run();
}
반응형
반응형

3~4번에 쓰이는 추상 클래스 LoopAdder 입니다.

class LoopAdder { // 추상 클래스 
	string name; // 루프의 이름 
	int x, y, sum; // x에서 y까지의 합은 sum 
	void read(); // x, y 값을 읽어 들이는 함수 
	void write(); // sum을 출력하는 함수 
protected:
	LoopAdder(string name = "") { // 루프의 이름을 받는다. 초깃값은 "" 
		this->name = name;
	}
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0; // 순수 가상 함수. 루프를 돌며 합을 구하는 함수 
public:
	void run(); // 연산을 진행하는 함수 
};

void LoopAdder::read() { // x, y 입력 
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더한다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}

void LoopAdder::write() { // 결과 sum 출력 
	cout << x << "에서 " << y << "까지의 합 = " << sum << " 입니다" << endl;
}

void LoopAdder::run() {
	read(); // x, y를 읽는다 
	sum = calculate(); // 루프를 돌면서 계산한다. 
	write(); // 결과 sum을 출력한다. 
}

 

문제

LoopAdder 클래스를 상속받아 다음 main() 함수와 실행 결과처럼 되도록  ForLoopAdder 클래스를 작성하라. ForLoopAdder 클래스의 calculate() 함수는 for 문을 이용하여 합을 구한다.

int main() {
	ForLoopAdder forLoop("For Loop");
	forLoop.run();
}

 

결과

While Loop:
처음 수에서 두번째 수까지 더합니다. 두 수를 입력하세요 >> 3 10
3에서 10까지의 합 = 52 입니다

 

소스코드

#include<iostream>
using namespace std;
class LoopAdder { // 추상 클래스 
	string name; // 루프의 이름 
	int x, y, sum; // x에서 y까지의 합은 sum 
	void read(); // x, y 값을 읽어 들이는 함수 
	void write(); // sum을 출력하는 함수 
protected:
	LoopAdder(string name = "") { // 루프의 이름을 받는다. 초깃값은 "" 
		this->name = name;
	}
	int getX() { return x; }
	int getY() { return y; }
	virtual int calculate() = 0; // 순수 가상 함수. 루프를 돌며 합을 구하는 함수 
public:
	void run(); // 연산을 진행하는 함수 
};

void LoopAdder::read() { // x, y 입력 
	cout << name << ":" << endl;
	cout << "처음 수에서 두번째 수까지 더한다. 두 수를 입력하세요 >> ";
	cin >> x >> y;
}

void LoopAdder::write() { // 결과 sum 출력 
	cout << x << "에서 " << y << "까지의 합 = " << sum << " 입니다" << endl;
}

void LoopAdder::run() {
	read(); // x, y를 읽는다 
	sum = calculate(); // 루프를 돌면서 계산한다. 
	write(); // 결과 sum을 출력한다. 
}

class ForLoopAdder : public LoopAdder {
	string name;
public:
	ForLoopAdder(string name = "") : LoopAdder(name) { this->name = name; }
	virtual int calculate() {
		int sum = 0;
		for (int i = getX(); i <= getY(); i++)
			sum += i;
		return sum;
	}
};

int main() {
	ForLoopAdder forLoop("For Loop");
	forLoop.run();
}
반응형
반응형

1~2번에 쓰이는 단위변환 추상 클래스 Converter입니다.

#include<iostream>
using namespace std;
class Converter {
protected:
	double ratio;
	virtual double convert(double src) = 0; //src를 다른 단위로 변환한다.
	virtual string getSourceString() = 0; //src 단위 명칭
	virtual string getDestString() = 0; //dest 단위 명칭
public:
	Converter(double ratio) { this->ratio = ratio; }
	void run() {
		double src;
		cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. ";
		cout << getSourceString() << "을 입력하세요>> ";
		cin >> src;
		cout << "변환 결과 : " << convert(src) << getDestString() << endl;
	}
};

 

문제

Converter 클래스를 상속받아 km를 mile(마일)로 변환하는 KmToMile 클래스를 작성하라. main() 함수와 실행 결과는 다음과 같다.

int main()
{
	KmToMile toMile(1.609344); //1mile은 1.609344km
	toMile.run();
}

 

결과

Km을 Mile로 바꿉니다. Km을 입력하세요>> 25
반환 결과 : 15.5343Mile

 

소스코드

#include<iostream>
using namespace std;
class Converter {
protected:
	double ratio;
	virtual double convert(double src) = 0; //src를 다른 단위로 변환한다.
	virtual string getSourceString() = 0; //src 단위 명칭
	virtual string getDestString() = 0; //dest 단위 명칭
public:
	Converter(double ratio) { this->ratio = ratio; }
	void run() {
		double src;
		cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. ";
		cout << getSourceString() << "을 입력하세요>> ";
		cin >> src;
		cout << "변환 결과 : " << convert(src) << getDestString() << endl;
	}
};
class KmToMile : public Converter {
	double mile;
public:
	KmToMile(double mile) : Converter(mile) { this->mile = mile; }
	virtual double convert(double src) { return src / mile; }
	virtual string getSourceString() { return "Km"; }
	virtual string getDestString() { return "Mile"; }
};
int main()
{
	KmToMile toMile(1.609344); //1mile은 1.609344km
	toMile.run();
}

 

반응형
반응형

1~2번에 쓰이는 단위변환 추상 클래스 Converter입니다.

#include<iostream>
using namespace std;
class Converter {
protected:
	double ratio;
	virtual double convert(double src) = 0; //src를 다른 단위로 변환한다.
	virtual string getSourceString() = 0; //src 단위 명칭
	virtual string getDestString() = 0; //dest 단위 명칭
public:
	Converter(double ratio) { this->ratio = ratio; }
	void run() {
		double src;
		cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. ";
		cout << getSourceString() << "을 입력하세요>> ";
		cin >> src;
		cout << "변환 결과 : " << convert(src) << getDestString() << endl;
	}
};

 

문제

Converter 클래스를 상속받아 달러를 원화로 환산하는 WonToDollar 클래스를 작성하라. main() 함수와 실행 결과는 다음과 같다.

int main()
{
	WonToDallar wd(1010); //1달러에 10101원
	wd.run();
}

 

결과

원을 달러로 바꿉니다. 원을 입력하세요>> 10000
변환 결과 : 9.90099달러

 

소스코드

#include<iostream>
using namespace std;
class Converter {
protected:
	double ratio;
	virtual double convert(double src) = 0; //src를 다른 단위로 변환한다.
	virtual string getSourceString() = 0; //src 단위 명칭
	virtual string getDestString() = 0; //dest 단위 명칭
public:
	Converter(double ratio) { this->ratio = ratio; }
	void run() {
		double src;
		cout << getSourceString() << "을 " << getDestString() << "로 바꿉니다. ";
		cout << getSourceString() << "을 입력하세요>> ";
		cin >> src;
		cout << "변환 결과 : " << convert(src) << getDestString() << endl;
	}
};
class WonToDallar : public Converter
{
	int krw;
public:
	WonToDallar(int krw) : Converter(krw) { this->krw = krw; }
	virtual double convert(double src) {
		return src / krw;
	}
	virtual string getSourceString() {
		return "원";
	}
	virtual string getDestString() {
		return "달러";
	}
};
int main()
{
	WonToDallar wd(1010); //1달러에 10101원
	wd.run();
}

 

반응형

+ Recent posts