10. 그래픽 편집기 작성 [난이도 7]
- Vector<Shape> 이용
- 추상 클래스 Shape와 이를 상속받는 Line, Rect, Circle 클래스
- "삽입", "삭제", "모두 보기", "종료" 4가지 그래픽 편집 기능
abstract class Shape {
public Shape() {}
public void paint() {draw();}
abstract public void draw();
}
class Line extends Shape{
@Override
public void draw() {
System.out.println("Line");
}
}
class Rect extends Shape{
@Override
public void draw() {
System.out.println("Rect");
}
}
class Circle extends Shape{
@Override
public void draw() {
System.out.println("Circle");
}
}
>> 실행 예시
Shape 클래스
abstract class Shape {
abstract public void draw();
}
class Line extends Shape{
@Override
public void draw() {
System.out.println("Line");
}
}
class Rect extends Shape{
@Override
public void draw() {
System.out.println("Rect");
}
}
class Circle extends Shape{
@Override
public void draw() {
System.out.println("Circle");
}
}
Shape 생성자랑 paint() 메소드는 굳이 없어도 될 것 같아서 삭제했습니다
Editor 클래스
import java.util.Vector;
public class Editor {
Vector<Shape> v=new Vector<>();
public void add(int input2) {
switch(input2) {
case 1:
v.add(new Line());
break;
case 2:
v.add(new Rect());
break;
case 3:
v.add(new Circle());
break;
default:
break;
}
}
public void remove(int index) {
if(index>v.size())
System.out.println("삭제할 수 없습니다.");
else {
System.out.println(index+"번째 도형을 삭제합니다.");
v.remove(index-1);
}
}
public void showAll() {
for(int i=0; i<v.size(); i++)
v.get(i).draw();
}
}
GraphicEx 클래스(main)
import java.util.Scanner;
public class GraphicEx {
String name;
public GraphicEx(String name) {
this.name=name;
}
public void run() {
System.out.println("그래픽 에디터 "+name+"을(를) 실행합니다.");
Editor e=new Editor();
Scanner scanner=new Scanner(System.in);
while(true) {
System.out.println();
System.out.print("삽입(1), 삭제(2), 모두 보기(3), 종료(4) >> ");
int input1=scanner.nextInt();
switch(input1) {
case 1:
System.out.print("Line(1), Rect(2), Circle(3) >> ");
int input2=scanner.nextInt();
e.add(input2);
break;
case 2:
System.out.print("삭제할 도형의 위치 >> ");
int index=scanner.nextInt();
e.remove(index);
break;
case 3:
e.showAll();
break;
case 4:
System.out.println(name+"을(를) 종료합니다.");
return;
default:
System.out.println("입력 오류");
break;
}
}
}
public static void main(String[] args) {
GraphicEx g=new GraphicEx("beauty");
g.run();
}
}
11. 나라와 수도 맞추기 게임 [난이도 7]
>> 실행 예시
(1)
- 나라 이름(country)과 수도(capital)을 필드로 가진 Nation 클래스
- Vector<Nation> 컬렉션을 이용해 프로그램 작성
Nation 클래스
public class Nation {
String country;
String capital;
public Nation(String country, String capital) {
this.country=country;
this.capital=capital;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Nation nation = (Nation) obj;
return country.equals(nation.country) && capital.equals(nation.capital);
}
@Override
public int hashCode() {
return country.hashCode() + capital.hashCode();
}
}
Game 클래스
import java.util.Scanner;
import java.util.Vector;
public class Game {
Vector<Nation> v=new Vector<>();
Scanner scanner=new Scanner(System.in);
public void addNation() {
System.out.println("현재 "+v.size()+"개 나라와 수도가 입력되어 있습니다.");
while(true) {
System.out.print("나라와 수도 입력("+(v.size()+1)+") >> ");
String[] input=scanner.nextLine().split(" ");
if(input[0].equals("그만")) break;
String country=input[0];
String capital=input[1];
Nation newNation=new Nation(country, capital);
if(!v.contains(newNation)) {
v.add(newNation);
}
else {
System.out.println(country+"는 이미 있습니다!");
newNation=null; //메모리 회수
}
}
}
public void quiz() {
while(true) {
int index=(int)(Math.random()*(v.size()));
String question=v.get(index).country;
String answer=v.get(index).capital;
System.out.print(question+"의 수도는? >> ");
String userAnswer=scanner.next();
if(userAnswer.equals("그만"))
break;
else if(userAnswer.equals(answer))
System.out.println("정답!!");
else
System.out.println("아닙니다!!");
}
}
}
NationQuizEx 클래스(main)
import java.util.Scanner;
public class NationQuizEx {
public void run() {
Scanner scanner=new Scanner(System.in);
Game g=new Game();
System.out.println("**** 수도 맞추기 게임을 시작합니다. ****");
while(true) {
System.out.println();
System.out.print("입력: 1, 퀴즈: 2, 종료: 3 >> ");
int input=scanner.nextInt();
switch(input) {
case 1:
g.addNation();
break;
case 2:
g.quiz();
break;
case 3:
System.out.println("게임을 종료합니다.");
return;
default:
System.out.println("입력 오류");
break;
}
}
}
public static void main(String[] args) {
NationQuizEx n=new NationQuizEx();
n.run();
}
}
(2)
- 위 프로그램을 HashMap<String, String>을 이용해 작성
- K=나라 이름, V=수도
Game 클래스
import java.util.*;
public class Game {
HashMap<String, String> hm=new HashMap<>();
Set<String> set=hm.keySet();
Scanner scanner=new Scanner(System.in);
public void addNation() {
System.out.println("현재 "+hm.size()+"개 나라와 수도가 입력되어 있습니다.");
while(true) {
System.out.print("나라와 수도 입력("+(hm.size()+1)+") >> ");
String[] input=scanner.nextLine().split(" ");
if(input[0].equals("그만")) break;
String country=input[0];
String capital=input[1];
Nation newNation=new Nation(country, capital);
if(!set.contains(newNation)) {
hm.put(newNation.capital, newNation.country);
}
else {
System.out.println(country+"는 이미 있습니다!");
newNation=null; //메모리 회수
}
}
}
public void quiz() {
while(true) {
Object[] setArr=set.toArray();
int index=(int)(Math.random()*(hm.size()));
String question=setArr[index].toString();
String answer=hm.get(question);
System.out.print(question+"의 수도는? >> ");
String userAnswer=scanner.next();
if(userAnswer.equals("그만"))
break;
else if(userAnswer.equals(answer))
System.out.println("정답!!");
else
System.out.println("아닙니다!!");
}
}
}
Game 클래스만 수정하면 됩니다
12. 7장 오픈챌린지를 수정하여 사용자가 단어를 삽입하는 기능 추가 [난이도 8]
>> 실행 화면
단어 삽입 메소드만 추가하면 됩니다
import java.util.*;
public class WordQuizEx {
String name;
Scanner scanner=new Scanner(System.in);
Vector<Word> v=new Vector<>();
public WordQuizEx(String name) {
this.name=name;
}
public void setWords() {
v.add(new Word("love", "사랑"));
v.add(new Word("animal", "동물"));
v.add(new Word("rice", "밥"));
v.add(new Word("java", "자바"));
v.add(new Word("flower", "꽃"));
v.add(new Word("baby", "아기"));
v.add(new Word("dog", "개"));
v.add(new Word("friend", "친구"));
}
public void addWords() {
System.out.println();
System.out.println("'그만'을 입력하면 입력을 종료합니다.");
scanner.nextLine(); //계속 ArrayIndexOutOfBoundsException오류가 나서 한번 거르고 시작
while(true) {
System.out.print("영어 한글 입력 >> ");
String input=scanner.nextLine();
if(input.equals("그만"))
break;
String[] inputArr=input.split(" ");
String eng=inputArr[0];
String kor=inputArr[1];
v.add(new Word(eng, kor));
}
}
public void showQuestion() {
System.out.println();
System.out.println("단어 테스트를 시작합니다. -1을 입력하면 종료합니다.");
System.out.println("현재 "+v.size()+"개의 단어가 들어 있습니다.");
while(true) {
System.out.println();
int answerIndex=(int)(Math.random()*v.size()); //랜덤 번호
String question=v.get(answerIndex).getEng(); //해당하는 영어 단어
System.out.println(question+"?");
scanner.nextLine();
Question mq=new Question(answerIndex, v.size());
for(int i=0; i<4; i++) {
System.out.print("("+(i+1) + ")"+v.get(mq.ex[i]).getKor()+" ");
}
System.out.print(":>");
int sel = scanner.nextInt(); // 사용자가 고른 번호
if(sel == -1) // -1 입력 시 종료
return;
else if(mq.ex[(sel-1)]==answerIndex)
System.out.println("Excellent!!");
else
System.out.println("No. !!");
}
}
public void run() {
setWords();
System.out.printf("**** 영어 단어 테스트 프로그램 \"%s\"입니다 ****\n", name);
while(true) {
System.out.println();
System.out.print("단어 테스트:1, 단어 삽입:2, 종료:3 >> ");
int choice=scanner.nextInt();
switch(choice) {
case 1:
showQuestion();
break;
case 2:
addWords();
break;
case 3:
System.out.println("\""+name+"\"을(를) 종료합니다.");
return;
default:
break;
}
}
}
public static void main(String[] args) {
WordQuizEx wq=new WordQuizEx("명품영어");
wq.run();
}
}
13. 명령을 실행하는 소프트웨어 작성 [난이도 9]
- mov, add, sub, jn0, prt 5가지 명령
- mov sum 0은 sum 변수에 0을 삽입
- add sum i는 sum 변수에 i를 더함
- sub n 1은 n의 값을 1 감소
- jn0 n 3은 n이 0이 아니면 3번째 명령으로 돌아가도록 처리
- prt sum 0은 sum의 값을 출력하고 프로그램 종료
- go는 지금까지 입력한 프로그램을 처음부터 실행하도록 하는 지시어
>> 실행 예시
CommandExector 클래스
import java.util.*;
public class CommandExecutor {
String name;
HashMap<String, Integer> variables=new HashMap<>(); //변수 저장할 해시맵
List<String[]> commands=new ArrayList<>(); //입력받은 명령 리스트
boolean isRunning=false;
String prtString;
int prtValue;
public CommandExecutor(String name) {
this.name=name;
}
public void addCommand(String command) {
commands.add(command.split(" ")); //띄어쓰기 단위로 분할해서 List에
}
public void run() {
isRunning=true;
int pointer=0; //현재 실행 중인 명령어 인덱스
while (isRunning) {
if (pointer>=commands.size()) {
break;
}
String[] command=commands.get(pointer);
switch (command[0]) {
case "mov":
mov(command[1], getValue(command[2]));
pointer++;
break;
case "add":
add(command[1], getValue(command[2]));
pointer++;
break;
case "sub":
sub(command[1], getValue(command[2]));
pointer++;
break;
case "jn0":
pointer=jn0(command[1], getValue(command[2])) ? getValue(command[2]) : pointer+1;
break;
case "prt":
prt(variables, command[1]);
isRunning = false;
break;
default:
break;
//throw new IllegalArgumentException("Unknown command: " + command[0]);
}
}
}
public void mov(String var, int value) {
variables.put(var, value);
}
public void add(String var, int value) {
variables.put(var, variables.getOrDefault(var, 0)+value);
}
public void sub(String var, int value) {
variables.put(var, variables.getOrDefault(var, 0)-value);
}
public boolean jn0(String var, int target) {
return variables.getOrDefault(var, 0) != 0;
}
public void prt(HashMap<String, Integer> hm, String var) {
System.out.println("[prt "+var+" 0]");
Set<String> set=hm.keySet();
Object[] setArr=set.toArray();
for(int i=0; i<setArr.length; i++) {
System.out.print(setArr[i].toString().toUpperCase()+": "+hm.get(setArr[i])+" ");
}
System.out.println();
System.out.println("출력할 결과는 "+variables.get(var)+". 프로그램 실행 끝");
}
public int getValue(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) { //변수로 연산해야 할 때
if (variables.containsKey(str)) {
return variables.get(str);
} else {
throw new IllegalArgumentException("입력 오류");
}
}
}
public static void main(String[] args) {
CommandExecutor executor = new CommandExecutor("수퍼컴");
Scanner scanner = new Scanner(System.in);
System.out.println(executor.name+"이 작동합니다. 프로그램을 입력해주세요. go를 입력하면 작동합니다.");
while (true) {
System.out.print(">> ");
String input = scanner.nextLine();
if (input.equalsIgnoreCase("go")) {
break;
}
executor.addCommand(input);
}
System.out.println();
executor.run();
}
}
합쳤어요
복잡해서 ㅎ;
'java > 예제&실습' 카테고리의 다른 글
[명품자바] 7장 실습문제(5~9) (0) | 2024.07.01 |
---|---|
[명품자바] 6장 실습문제 (0) | 2024.06.27 |
[명품자바] 8장 오픈챌린지 (0) | 2024.06.25 |
[명품자바] 7장 오픈챌린지 (0) | 2024.06.20 |
[명품자바] 6장 오픈챌린지 (0) | 2024.06.19 |