Skip to content
Home » 명품 자바 프로그래밍 5 장 실습 문제 | 자바프로그래밍실습 5장 16286 투표 이 답변

명품 자바 프로그래밍 5 장 실습 문제 | 자바프로그래밍실습 5장 16286 투표 이 답변

당신은 주제를 찾고 있습니까 “명품 자바 프로그래밍 5 장 실습 문제 – 자바프로그래밍실습 5장“? 다음 카테고리의 웹사이트 https://kk.taphoamini.com 에서 귀하의 모든 질문에 답변해 드립니다: https://kk.taphoamini.com/wiki/. 바로 아래에서 답을 찾을 수 있습니다. 작성자 전수빈 이(가) 작성한 기사에는 조회수 824회 및 좋아요 6개 개의 좋아요가 있습니다.

명품 자바 프로그래밍 5 장 실습 문제 주제에 대한 동영상 보기

여기에서 이 주제에 대한 비디오를 시청하십시오. 주의 깊게 살펴보고 읽고 있는 내용에 대한 피드백을 제공하세요!

d여기에서 자바프로그래밍실습 5장 – 명품 자바 프로그래밍 5 장 실습 문제 주제에 대한 세부정보를 참조하세요

자바프로그래밍실습 5장
대구가톨릭대학교 자바프로그래밍실습 5장 강의 영상

명품 자바 프로그래밍 5 장 실습 문제 주제에 대한 자세한 내용은 여기를 참조하세요.

명품 자바 프로그래밍 5장 실습 문제 / 2021.11.16 – 코딩은 즐거워

명품 자바 프로그래밍 5장 실습 문제 / 2021.11.16 … static vo main(String args[]) { ColorPoint cp = new ColorPoint(5, 5, “Yellow”); cp.

+ 자세한 내용은 여기를 클릭하십시오

Source: cow-kite24.tistory.com

Date Published: 7/29/2021

View: 800

명품 자바 프로그래밍(개정4판) 제 5장 실습문제

명품 자바 프로그래밍(개정4판) 제 5장 실습문제 … 5번. Point{ private int x,y; public Point(int x,int y) {this.x=x;this.y=y;} …

+ 더 읽기

Source: khu98.tistory.com

Date Published: 6/20/2022

View: 1599

명품 JAVA Programming 5장 실습문제 정답 – 문풀이 – 티스토리

명품 JAVA Programming 5장 실습문제 정답 명품 JAVA Programming 5장 실습문제 정답 1번, 2번 public TV { private int size; public TV(int …

+ 여기에 더 보기

Source: tistorysolution.tistory.com

Date Published: 3/4/2022

View: 2375

명품 자바 프로그래밍 5장 OpenChallenge&실습문제

명품 자바 프로그래밍 5장 OpenChallenge&실습문제. YUNOgrammer 2021. 1. 5. 00:32. 개인적으로 이 상속 파트가 실습문제들이 어렵습니다.

+ 여기에 보기

Source: yunoprogram.tistory.com

Date Published: 12/30/2021

View: 9658

명품 JAVA Programming 5장 실습문제 9번, 10번, 11번

명품 JAVA Programming 5장 실습문제 9번, 10번, 11번. 창조적생각 2021. 7. 8. 21:37. 9번. 다음 Stack 인터페이스를 상속받아 실수를 저장하는 StringStack …

+ 자세한 내용은 여기를 클릭하십시오

Source: operstu1.tistory.com

Date Published: 11/20/2022

View: 2348

<명품 JAVA Programming> – Chapter5 연습문제(9, 10, 11, 12 …

<명품 JAVA Programming> – Chapter5 연습문제(9, 10, 11, 12, 13, 14) · 프로그래밍/JAVA(자바) 2020. … [명품 JAVA] 5장 실습문제(9~14) (상속).

+ 여기에 보기

Source: kiffblog.tistory.com

Date Published: 7/9/2021

View: 6942

주제와 관련된 이미지 명품 자바 프로그래밍 5 장 실습 문제

주제와 관련된 더 많은 사진을 참조하십시오 자바프로그래밍실습 5장. 댓글에서 더 많은 관련 이미지를 보거나 필요한 경우 더 많은 관련 기사를 볼 수 있습니다.

자바프로그래밍실습 5장
자바프로그래밍실습 5장

주제에 대한 기사 평가 명품 자바 프로그래밍 5 장 실습 문제

  • Author: 전수빈
  • Views: 조회수 824회
  • Likes: 좋아요 6개
  • Date Published: 2020. 4. 13.
  • Video Url link: https://www.youtube.com/watch?v=-CZ_VOkgEIo

명품 자바 프로그래밍 5장 실습 문제 / 2021.11.16

728×90

1.

package Chapter5; class TV { private int size; public TV(int size) { this.size = size; } protected int getSize() { return size; } } class ColorTV extends TV{ private int Color; public ColorTV(int size, int Color) { super(size); this.Color = Color; } public void printProperty() { System.out.println(super.getSize()+”인치 ” + Color+”컬러”); } } public class Exercise { public static void main(String [] args) { ColorTV myTV = new ColorTV(32, 1024); myTV.printProperty(); } }

2.

package Chapter5; class TV { private int size; public TV(int size) { this.size = size; } protected int getSize() { return size; } } class ColorTV extends TV{ private int Color; public ColorTV(int size, int Color) { super(size); this.Color = Color; } public void printProperty() { System.out.println(super.getSize()+”인치 ” + Color+”컬러”); } } class IPTV extends ColorTV{ private String address; public IPTV(String address, int size, int Color) { super(size, Color); this.address = address; } public void printProperty() { System.out.print(“나의 IPTV는 ” + this.address +” 주소의 “); super.printProperty(); } } public class Exercise { public static void main(String [] args) { IPTV iptv = new IPTV(“192.1.1.2”, 32, 2048); iptv.printProperty(); } }

3.

package Chapter5; import java.util.Scanner; abstract class Converter { abstract protected double convert(double src); // 추상 메소드 abstract protected String getSrcString(); // 추상 메소드 abstract protected String getDestString(); // 추상 메소드 protected double ratio; // 비율 public void run() { Scanner scanner = new Scanner(System.in); System.out.println(getSrcString()+”을 “+getDestString()+”로 바꿉니다.”); System.out.print(getSrcString()+”을 입력하세요>> “); double val = scanner.nextDouble(); double res = convert(val); System.out.println(“변환 결과: “+res+getDestString()+”입니다”); scanner.close(); } } class Won2Dollar extends Converter { public Won2Dollar(double ratio) { this.ratio = ratio; } protected double convert(double src) { return src/ratio; } protected String getSrcString() { return “원”; } protected String getDestString() { return “달러”; } } public class Exercise { public static void main(String args[]) { Won2Dollar toDollar = new Won2Dollar(1200); toDollar.run(); } }

4.

package Chapter5; import java.util.Scanner; abstract class Converter { abstract protected double convert(double src); // 추상 메소드 abstract protected String getSrcString(); // 추상 메소드 abstract protected String getDestString(); // 추상 메소드 protected double ratio; // 비율 public void run() { Scanner scanner = new Scanner(System.in); System.out.println(getSrcString()+”을 “+getDestString()+”로 바꿉니다.”); System.out.print(getSrcString()+”을 입력하세요>> “); double val = scanner.nextDouble(); double res = convert(val); System.out.println(“변환 결과: “+res+getDestString()+”입니다”); scanner.close(); } } class Km2Mile extends Converter { public Km2Mile(double ratio) { this.ratio = ratio; } protected double convert(double src) { return src/ratio; } protected String getSrcString() { return “Km”; } protected String getDestString() { return “mile”; } } public class Exercise { public static void main(String args[]) { Km2Mile toMile = new Km2Mile(1.6); toMile.run(); } }

5.

package Chapter5; 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 { private String color; public ColorPoint(int x, int y, String color) { super(x, y); this.color = color; } public void setXY (int x, int y) { move(x, y); } public void setColor (String color) { this.color = color; } public String toString() { return this.color + “색의 (” + getX() + “,” + getY() + “)의 점”; } } public class Exercise { 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.

package Chapter5; 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 { private String color; public ColorPoint() { super(0,0); this.color = “BLACK”; } public ColorPoint(int x, int y) { super(x, y); this.color = “BLACK”; } public void setXY (int x, int y) { move(x, y); } public void setColor (String color) { this.color = color; } public String toString() { return this.color + “색의 (” + getX() + “,” + getY() + “)의 점”; } } public class Exercise { public static void main(String args[]) { ColorPoint zeroPoint = new ColorPoint(); System.out.println(zeroPoint.toString() + “입니다.”); ColorPoint cp = new ColorPoint(10, 10); cp.setXY(5, 5); cp.setColor(“RED”); System.out.println(cp.toString() + “입니다.”); } }

7.

package Chapter5; 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 Point3D extends Point { private int z; public Point3D(int x, int y, int z) { super(x, y); this.z = z; } public int getZ() { return z; } public String toString () { return “(” + getX() + “,” + getY() + “,” + getZ() + “)의 점”; } protected void moveUp() { this.z += 1; } protected void moveDown() { this.z -= 1; } protected void move(int x, int y, int z) { move(x, y); this.z = z;} } public class Exercise { public static void main(String args[]) { Point3D p = new Point3D(1, 2, 3); System.out.println(p.toString() + “입니다.”); p.moveUp(); System.out.println(p.toString() + “입니다.”); p.moveDown(); p.move(10, 10); System.out.println(p.toString() + “입니다.”); p.move(100, 200, 300); System.out.println(p.toString() + “입니다.”); } }

8.

package Chapter5; 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) { super(x, y); if(x < 0 || y < 0) super.move(0, 0); } protected void move(int x, int y) { if(x > 0 && y > 0) { super.move(x, y); } } public String toString() { return “(” + getX() + “,” + getY() + “)의 점”; } } public class Exercise { 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.

package Chapter5; import java.util.Scanner; interface Stack { int length(); int capacity(); String pop(); boolean push(String val); } class StringStack implements Stack{ private int size; private int index; // 배열의 인덱스 번호 private String [] StackArray; public StringStack(int size) { this.size = size; StackArray = new String [size]; this.index = -1; } public int length() { return index+1; } public int capacity() { return StackArray.length; } public String pop() { String popStr; if(index == -1) return null; popStr = StackArray[index]; index–; return popStr; } public boolean push(String val) { if(index+1 < size) { index++; StackArray[index] = val; return true; } else { return false; } } } public class Exercise { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("총 스택 저장 공간의 크기 입력 >> “); int size = sc.nextInt(); StringStack Stack = new StringStack(size); while(true) { System.out.print(“문자열 입력 >> “); String val = sc.next(); if(val.equals(“그만”)) break; if(!Stack.push(val)) System.out.println(“스택이 꽉 차서 푸시 불가!”); } System.out.print(“스택에 저장된 모든 문자열 팝 : “); for(int i=0; i> “); int a = sc.nextInt(); int b = sc.nextInt(); char op = sc.next().charAt(0); switch(op) { case ‘+’: Add ad = new Add(); ad.setValue(a, b); System.out.println(ad.calculate()); break; case ‘-‘: Sub sb = new Sub(); sb.setValue(a, b); System.out.println(sb.calculate()); break; case ‘*’: Mul ml = new Mul(); ml.setValue(a, b); System.out.println(ml.calculate()); break; case ‘/’: Div dv = new Div(); dv.setValue(a, b); System.out.println(dv.calculate()); break; } } }

12.

13.

package Chapter5; interface Shape{ final double PI = 3.14; void draw(); double getArea(); default public void redraw() { System.out.print(“— 다시 그립니다. “); draw(); } } class Circle implements Shape{ private int radius; public Circle(int radius) { this.radius = radius; } public void draw() { System.out.println(“반지름이 ” + this.radius + “인 원입니다.”); } public double getArea() { return PI * radius * radius; } } public class Exercise { public static void main(String args[]) { Shape donut = new Circle(10); donut.redraw(); System.out.println(“면적은 ” + donut.getArea()); } }

14.

package Chapter5; interface Shape{ final double PI = 3.14; void draw(); double getArea(); default public void redraw() { System.out.print(“— 다시 그립니다. “); draw(); } } class Circle implements Shape{ private int radius; public Circle(int radius) { this.radius = radius; } public void draw() { System.out.println(“반지름이 ” + this.radius + “인 원입니다.”); } public double getArea() { return PI * radius * radius; } } class Oval implements Shape{ private int a, b; public Oval(int a, int b) { this.a = a; this.b = b; } public void draw() { System.out.println(this.a+”x”+this.b+”에 내접하는 타원입니다.”); } public double getArea() { return PI * a * b; } } class Rect implements Shape{ private int a, b; public Rect(int a, int b) { this.a = a; this.b = b; } public void draw() { System.out.println(this.a+”x”+this.b+”크기의 사각형입니다.”); } public double getArea() { return a*b; } } public class Exercise { public static void main(String args[]) { Shape [] list = new Shape [3]; list[0] = new Circle(10); list[1] = new Oval(20, 30); list[2] = new Rect(10, 40); for(int i=0; i

명품 자바 프로그래밍(개정4판) 제 5장 실습문제

728×90

반응형

1번.

class TV{ private int size; public TV(int size) { this.size=size;} protected int getSize() { return size;} } class ColorTV extends TV{ private int colorSize; public ColorTV(int size,int colorSize) { super(size); this.colorSize=colorSize; } public void printProperty() { System.out.println(getSize()+”인치 “+colorSize+”컬러”); } } public class p0501 { public static void main(String[] args) { // TODO Auto-generated method stub ColorTV myTV= new ColorTV(32,1024); myTV.printProperty(); } }

2번.

class TV{ private int size; public TV(int size) { this.size=size;} protected int getSize() { return size;} } class ColorTV extends TV{ private int colorSize; public ColorTV(int size,int colorSize) { super(size); this.colorSize=colorSize; } public void printProperty() { System.out.println(getSize()+”인치 “+colorSize+”컬러”); } } class IPTV extends ColorTV{ String ipAddress; public IPTV(String ip,int size,int colorSize) { super(size,colorSize); ipAddress=ip; } @Override public void printProperty() { System.out.print(“나의 IPTV는 “+ipAddress+” 주소의 “); super.printProperty(); } } public class p0502 { public static void main(String[] args) { // TODO Auto-generated method stub IPTV iptv= new IPTV(“192.1.1.2”,32,2048); iptv.printProperty(); } }

3번.

import java.util.Scanner; abstract class Converter{ abstract protected double convert(double src); abstract protected String getSrcString(); abstract protected String getDestString(); protected double ratio; public void run() { Scanner scanner = new Scanner(System.in); System.out.println(getSrcString()+”을 “+getDestString()+”로 바꿉니다.”); System.out.print(getSrcString()+”을 입력하세요>> “); double val=scanner.nextDouble(); double res=convert(val); System.out.println(“변환 결과: “+res+getDestString()+”입니다.”); scanner.close(); } } class Won2Dollar extends Converter{ public Won2Dollar(double ratio) { this.ratio=ratio; } protected double convert(double src) { return src/ratio; } protected String getSrcString() { return “원”; } protected String getDestString() { return “달러”; } } public class p0503 { public static void main(String[] args) { // TODO Auto-generated method stub Won2Dollar toDollar=new Won2Dollar(1200); toDollar.run(); } }

4번.

import java.util.Scanner; abstract class Converter{ abstract protected double convert(double src); abstract protected String getSrcString(); abstract protected String getDestString(); protected double ratio; public void run() { Scanner scanner = new Scanner(System.in); System.out.println(getSrcString()+”을 “+getDestString()+”로 바꿉니다.”); System.out.print(getSrcString()+”을 입력하세요>> “); double val=scanner.nextDouble(); double res=convert(val); System.out.println(“변환 결과: “+res+getDestString()+”입니다.”); scanner.close(); } } class Km2Mile extends Converter{ public Km2Mile(double ratio) { this.ratio=ratio; } protected double convert(double src) { return src/ratio; } protected String getSrcString() { return “Km”; } protected String getDestString() { return “mile”; } } public class p0504 { public static void main(String[] args) { // TODO Auto-generated method stub Km2Mile toMile=new Km2Mile(1.6); toMile.run(); } }

5번.

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{ String color; public ColorPoint(int x,int y,String color) { super(x,y); this.color=color; } public void setXY(int x,int y) { move(x,y); } public void setColor(String color) { this.color=color; } public String toString() { return color+”색의 (“+getX()+”,”+getY()+”)의 점”; } } public class p0505 { 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번.

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{ String color; public ColorPoint() { super(0,0); color=”BLACK”; } public ColorPoint(int x,int y) { super(x,y); color=”BLACK”; } public ColorPoint(int x,int y,String color) { super(x,y); this.color=color; } public void setXY(int x,int y) { move(x,y); } public void setColor(String color) { this.color=color; } public String toString() { return color+”색의 (“+getX()+”,”+getY()+”)의 점”; } } public class p0506 { public static void main(String[] args) { // TODO Auto-generated method stub ColorPoint zeroPoint = new ColorPoint(); System.out.println(zeroPoint.toString()+”입니다.”); ColorPoint cp=new ColorPoint(10,10); cp.setXY(5, 5); cp.setColor(“RED”); System.out.println(cp.toString()+”입니다.”); } }

7번.

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{ int z; public Point3D(int x,int y,int z) { super(x,y); this.z=z; } public void moveUp() { z++; } public void moveDown() { z–; } public String toString() { return “(“+getX()+”,”+getY()+”,”+z+”)의 점”; } public void move(int x,int y,int z) { super.move(x, y); this.z=z; } } public class p0507 { public static void main(String[] args) { // TODO Auto-generated method stub Point3D p=new Point3D(1, 2, 3); System.out.println(p.toString()+”입니다.”); p.moveUp(); System.out.println(p.toString()+”입니다.”); p.moveDown(); p.move(10, 10); System.out.println(p.toString()+”입니다.”); p.move(100,200,300); System.out.println(p.toString()+”입니다.”); } }

8번.

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) { super(x,y); if(getX()<0||getY()<0) { move(0,0); } } public String toString() { return "("+getX()+","+getY()+")"+"의 점"; } protected void move(int x1,int y1) { if(x1<0||y1<0) { return; } else { super.move(x1, y1); } } } public class p0508 { public static void main(String[] args) { // TODO Auto-generated method stub 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번. import java.util.Scanner; interface Stack{ int length(); int capacity(); String pop(); boolean push(String val); } class StringStack implements Stack{ String[] arr; int len,cap; public StringStack(int n) { arr=new String[n]; len=0; cap=n; } public int length() { return len; } public int capacity() { return cap; } public String pop() { return arr[--len]; } public boolean push(String val) { if(len==cap) { System.out.println("스택이 꽉 차서 푸시 불가!"); return false; } else { arr[len++]=val; return true; } } public boolean isEmpty() { if(len==0) { return true; } else { return false; } } public void print() { System.out.print("스택에 저장된 모든 문자열 팝 :"); while(!isEmpty()) { System.out.print(" "+pop()); } System.out.println(); } } public class p0509 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); System.out.print("총 스택 저장 공간의 크기 입력 >>”); int n=sc.nextInt(); StringStack ss=new StringStack(n); String op; while(true) { System.out.print(“문자열 입력 >> “); op=sc.next(); if(op.equals(“그만”)) { break; } ss.push(op); } ss.print(); } }

10번.

abstract class PairMap{ protected String keyArray[]; protected String valueArray[]; abstract String get(String key); abstract void put(String key,String value); abstract String delete(String key); abstract int length(); } class Dictionary extends PairMap{ private int num; //생성자로 배열을 초기화 public Dictionary(int n) { num=0; keyArray=new String[n]; valueArray=new String[n]; } String get(String key) { for(int i=0;i>”); int a=sc.nextInt(); int b=sc.nextInt(); String op=sc.next(); Calc sp; switch(op.charAt(0)) { case ‘+’: sp=new Add(); break; case ‘-‘: sp=new Sub(); break; case ‘*’: sp=new Mul(); break; case ‘/’: sp=new Div(); break; default: return ; } sp.setValue(a, b); System.out.println(sp.calculate()); } }

12번.

import java.util.Scanner; abstract class Shape{ private Shape next; public Shape() { next=null; } public void setNext(Shape obj) { next=obj; } public Shape getNext() { return next; } public abstract void draw(); } class Line extends Shape{ public Line() { super(); } //오버라이딩 public void draw() { System.out.println(“Line”); } } class Rect extends Shape{ public Rect() { super(); } //오버라이딩 public void draw() { System.out.println(“Rect”); } } class Circle extends Shape{ public Circle() { super(); } //오버라이딩 public void draw() { System.out.println(“Circle”); } } class GraphicEditor{ private Shape head,tail; private Scanner sc; //기본생성자 public GraphicEditor(){ head=null; tail=null; sc=new Scanner(System.in); } //에디터 실행 메서드 void runEditor() { int choice; System.out.println(“그래픽 에디터 beauty을 실행합니다.”); do { System.out.print(“삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>”); choice=sc.nextInt(); switch(choice) { case 1: System.out.print(“Line(1), Rect(2), Circle(3)>>”); int option=sc.nextInt(); put(option); break; case 2: System.out.print(“삭제할 도형의 위치>>”); int index=sc.nextInt(); delete(index); break; case 3: print(); break; case 4: break; default: System.out.println(“다시 입력해주세요”); break; } }while(choice!=4); System.out.println(“beauty을 종료합니다.”); } //리스트에 넣는 메서드 void put(int num) { Shape g; //입력번호에 따라 Line,Rect,Circle객체 생성 switch(num) { case 1: g=new Line(); break; case 2: g=new Rect(); break; case 3: g=new Circle(); break; default: System.out.println(“다시입력해주세요”); return; } //리스트에 연결 if(head==null) { head=g; tail=g; } else { tail.setNext(g); tail=g; } return; } void delete(int index) { Shape cur=head; Shape temp=head; if(head==null) { System.out.println(“삭제할 수 없습니다.”); return; } //리스트에서 해당 인덱스의 노드 삭제 if(index==1) { if(head==tail) { tail=head=null; return; } else { head=head.getNext(); return; } } else { int i; for(i=1;i

명품 JAVA Programming 5장 실습문제 정답

반응형

728×170

명품 JAVA Programming 5장 실습문제 정답

명품 JAVA Programming 5장 실습문제 정답

1번, 2번

public class TV { private int size; public TV(int size) { this.size = size; } protected int getSize() { return size; } } class ColorTV extends TV { public int color; public ColorTV(int size, int color) { super(size); this.color = color; } public void printProperty() { System.out.println(getSize() + “인치 ” + color + “컬러”); } public static void main(String[] args) { ColorTV myTV = new ColorTV(32, 1024); myTV.printProperty(); } } class IPTV extends ColorTV { String address; public IPTV(String address, int size, int color) { super(size, color); this.address = address; } public void printProperty() { System.out.println(“나의 IPTV는 ” + address + ” 주소의 ” + getSize() + “인치 ” + color + “컬러”); } public static void main(String[] args) { IPTV iptv = new IPTV(“192.1.1.2”, 32, 2048); iptv.printProperty(); } }

3번

import java.util.Scanner; abstract class Converter { abstract protected double convert(double src); abstract protected String srcString(); abstract protected String destString(); protected double ratio; public void run() { Scanner scanner = new Scanner(System.in); System.out.println(srcString() + “을 ” + destString() + “로 바꿉니다.”); System.out.print(srcString() + “을 입력하세요>> “); double val = scanner.nextDouble(); double res = convert(val); System.out.println(“변환 결과: ” + res + destString() + “입니다”); scanner.close(); } } class Won2Dollar extends Converter { public Won2Dollar(double ratio) { this.ratio = ratio; } @Override protected double convert(double src) { return src / ratio; } @Override protected String srcString() { return “원”; } @Override protected String destString() { return “달러”; } public static void main(String args[]) { Won2Dollar toDollar = new Won2Dollar(1200); toDollar.run(); } }

4번

5번

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 { private String color; public ColorPoint(int x, int y, String color) { super(x, y); this.color = color; } public void setXY(int x, int y) { move(x, y); } public void setColor(String color) { this.color = color; } public String toString() { return color + “색의 {” + getX() + “,” + getY() + “)의점”; } } public class Pointex { 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번

class Point2 { private int x, y; public Point2() { this.x = 0; this.y = 0; } public Point2(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 ColorPoint2 extends Point2 { private String color; public ColorPoint2() { this.color = “Black”; } public ColorPoint2(int x, int y) { super(x, y); } public void setXY2(int x, int y) { move(x, y); } public void setColor2(String color) { this.color = color; } public String toString2() { return color + “색의 {” + getX() + “,” + getY() + “)의점”; } } public class Pointex2 { public static void main(String[] args) { ColorPoint2 zeroPoint = new ColorPoint2(); System.out.println(zeroPoint.toString2() + “입니다.”); ColorPoint2 cp = new ColorPoint2(10, 10); cp.setXY2(5, 5); cp.setColor2(“RED”); System.out.println(cp.toString2() + “입니다”); } }

7번

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; } } public class Point3D extends Point { private int z; public Point3D(int x, int y, int z) { super(x, y); this.z = z; } public int getZ() { return z; } public void moveUp() { z++; } public void moveDown() { z–; } public void move(int x, int y, int z) { move(x, y); this.z = z; } public String toString() { return “(” + getX() + “,” + getY() + “,” + getZ() + “)의 점”; } public static void main(String[] args) { Point3D p = new Point3D(1, 2, 3); System.out.println(p.toString() + “입니다.”); p.moveUp(); System.out.println(p.toString() + “입니다.”); p.moveDown(); p.move(10, 10); System.out.println(p.toString() + “입니다.”); p.move(100, 200, 300); System.out.println(p.toString() + “입니다.”); } }

8번

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; } } public class PositivePoint extends Point { public PositivePoint() { super(0, 0); } public PositivePoint(int x, int y) { super(x, y); if(x < 0 || y < 0) // 만일 x나 y가 음수이면 super.move(0, 0); // 다시 (0,0)으로 이동 } @Override protected void move(int x, int y) { // Point의 move() 오버라이딩 if(x > 0 && y > 0) super.move(x, y); else return; // 점을 이동시키지 않고 그냥 리턴 } public String toString() { return “(” + getX() + “,” + getY() + “)의 점”; } public static void main(String[] args) { PositivePoint p = new PositivePoint(); p.move(10, 10); System.out.println(p.toString() + “입니다.”); p.move(-5, 5); // 객체 p는 음수 공간으로 이동되지 않음 System.out.println(p.toString() + “입니다.”); PositivePoint p2 = new PositivePoint(-10, -10); System.out.println(p2.toString() + “입니다.”); } }

9번

interface Stack { int length(); int capacity(); String pop(); boolean push(String val); } public class StringStack implements Stack { private String[] element; private int tos; public StringStack(int capacity) { element = new String[capacity]; tos = -1; } @Override public int length() { return tos + 1; } @Override public int capacity() { return element.length; } @Override public String pop() { if (tos == -1) return null; String s = element[tos]; tos–; return s; } @Override public boolean push(String str) { if (tos == element.length – 1) return false; else { tos++; element[tos] = str; return true; } } } import java.util.*; public class StackApp { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“총 스택 저장 공간의 크기 입력 >> “); int n = scanner.nextInt(); StringStack ss = new StringStack(); while (true) { System.out.print(“문자열 입력 >> “); String str = scanner.next(); if (str.equals(“그만”)) break; boolean res = ss.push(str); if (res == false) { System.out.println(“스택이 꽉 차서 푸시 불가!”); } } System.out.print(“스택에 저장된 모든 문자열 팝 : “); int len = ss.length(); for (int i = 0; i < len; i++) { System.out.print(ss.pop() + " "); } scanner.close(); } } 10번 abstract class PairMap { protected String keyArray []; // key들을 저장하는 배열 protected String valueArray []; // value 들을 저장하는배열 abstract String get(String key); // key 값으로 value를 검색 abstract void put(String key, String value); // key와 value를 쌍으로 저장 abstract String delete(String key); // key 값을 가진 아이템(value와 함께)을 삭제. 삭제된 value 값 리턴 abstract int length(); // 현재 저장된 아이템의 개수 리턴 } class Dictionary extends PairMap { protected int count = 0; // 현재 저장된 아이템의 개수 public Dictionary(int capacity) { // 생성자 keyArray = new String [capacity]; valueArray = new String [capacity]; } @Override String get(String key) { for(int i=0; i>”); int a = scanner.nextInt(); int b = scanner.nextInt(); char operator = scanner.next().charAt(0); // 연산자를 문자로 변환 Calc exp; switch (operator) { case ‘+’: exp = new Add(); break; case ‘-‘: exp = new Sub(); break; case ‘*’: exp = new Mul(); break; case ‘/’: exp = new Div(); break; default: System.out.println(“잘못된 연산자입니다.”); scanner.close(); return; } exp.setValue(a, b); // 피연산자 a와 b 값을 객체에 저장 if(exp instanceof Div && b == 0) // 0으로 나누는 경우 System.out.println(“계산할 수 없습니다.”); else System.out.println(exp.calculate()); scanner.close(); } }

12번

public abstract class Shape { private Shape next; public Shape() { next = null;} public void setNext(Shape obj) {next = obj;} // 링크 연결 public Shape getNext() {return next;} public abstract void draw(); } public class Line extends Shape { @Override public void draw() { System.out.println(“Line”); } } public class Rect extends Shape { @Override public void draw() { System.out.println(“Rect”); } } public class Circle extends Shape { @Override public void draw() { System.out.println(“Circle”); } } import java.util.Scanner; public class GraphicEditor { private String name; private Scanner scanner = new Scanner(System.in); private Shape start=null, end=null; public GraphicEditor(String name) { this.name = name; } public void run() { System.out.println(“그래픽 에디터 ” + name + “을 실행합니다.”); int choice = 0; while (choice != 4) { int type, index; System.out.print(“삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>”); choice = scanner.nextInt(); switch (choice) { case 1: // 삽입 System.out.print(“Line(1), Rect(2), Circle(3)>>”); type = scanner.nextInt(); if (type < 1 || type > 3) { System.out.println(“잘못 선택하셨습니다.”); break; } insert(type); break; case 2: // 삭제 System.out.print(“삭제할 도형의 위치>>”); index = scanner.nextInt(); if (!delete(index)) { System.out.println(“삭제할 수 없습니다.”); } break; case 3: // 모두 보기 Shape p = start; while(p != null) { p.draw(); p = p.getNext(); } break; case 4: // 끝내기 break; default: System.out.println(“잘못 입력하셨습니다.”); } } System.out.println(name + “을 종료합니다.”); } private boolean delete(int index) { Shape current = start, previous = start; if (start == null) // 리스트가 빈 경우 return false; for (int i=0; i

명품 자바 프로그래밍 5장 OpenChallenge&실습문제

개인적으로 이 상속 파트가 실습문제들이 어렵습니다.

남의 코드 보는게 제일 어렵다고 이미 짜여있는 틀에서 본인 코드 삽입하기가 쉽지 않을거라 생각합니다.

저도 처음 학습할때 이파트 실습문제 풀면서 예시에 새로운 코드를 추가한다던지 하는 잘못된 방식으로 접근해서 푼것도 많습니다. 최대한 해보시다가 안되면 빠르게 답지 보고 이해하는게 좋을것 같습니다. 개인적으로 너무 어렵다면 OpenChallenge는 안푸셔도 될거 같아요. 하면 제일 좋습니다.

OpenChallenge.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 import java.util. Scanner ; abstract class GameObject { protected int distance; protected int x, y; public GameObject( int startX, int startY, int distance) { this .x = startX; this .y = startY; this .distance = distance; } public int getX() { return x;} public int getY() { return y;} public boolean collide(GameObject p) { if ( this .x = = p.getX() & & this .y = = p.getY()) return true ; else return false ; } protected abstract void move(); protected abstract char getShape(); } public class OpenChallenge { public static void main( String [] args) { Frame frame = new Frame(); frame.set(); frame.run(); } } class Bear extends GameObject{ public Bear( int startX, int startY, int distance) { super (startX, startY, distance); // TODO Auto-generated constructor stub } @Override protected void move() { Scanner sc_B = new Scanner ( System . in ); System . out . print ( “왼쪽(a), 아래(s), 위(d), 오른쪽(f) >>” ); String trig = sc_B.next(); switch (trig) { case “a” : Frame.map[y][x] = ‘-‘ ; x – = distance; Frame.map[y][x] = getShape(); break ; case “s” : Frame.map[y][x] = ‘-‘ ; y + = distance; Frame.map[y][x] = getShape(); break ; case “d” : Frame.map[y][x] = ‘-‘ ; y + = distance; Frame.map[y][x] = getShape(); break ; case “f” : Frame.map[y][x] = ‘-‘ ; x + = distance; Frame.map[y][x] = getShape(); break ; } } @Override protected char getShape() { return ‘B’ ; } } class Fish extends GameObject{ public Fish( int startX, int startY, int distance) { super (startX, startY, distance); // TODO Auto-generated constructor stub } @Override protected void move() { // TODO Auto-generated method stub switch (( int )(Math.random() * 3 )) { case 0 : if (x = = 0 ) { Frame.map[y][x] = getShape(); } else { Frame.map[y][x] = ‘-‘ ; x – = distance; Frame.map[y][x] = getShape(); } break ; case 1 : if (y = = 9 ) { Frame.map[y][x] = getShape(); } else { Frame.map[y][x] = ‘-‘ ; y + = distance; Frame.map[y][x] = getShape(); } break ; case 2 : if (y = = 19 ) { Frame.map[y][x] = getShape(); } else { Frame.map[y][x] = ‘-‘ ; y + = distance; Frame.map[y][x] = getShape(); } break ; case 3 : if (x = = 9 ) { Frame.map[y][x] = getShape(); } else { Frame.map[y][x] = ‘-‘ ; x + = distance; Frame.map[y][x] = getShape(); } break ; } } @Override protected char getShape() { // TODO Auto-generated method stub return ‘@’ ; } } class Frame{ static char [][] map = new char [ 10 ][ 20 ]; //map은 다른 클래스에서도 변화시킬 예정이니 static으로 선언해 놓았습니다. Bear bear = new Bear( 0 , 0 , 1 ); Fish fish = new Fish( 5 , 5 , 1 ); public void set(){ //초기설정 for ( int i = 0 ;i < 10 ;i + + ) { for ( int e = 0 ;e < 20 ;e + + ) { map[i][e] = '-' ; } } map[ 0 ][ 0 ] = bear.getShape(); map[ 5 ][ 5 ] = fish.getShape(); } public void printMap() { for ( int i = 0 ;i < 10 ;i + + ) { for ( int e = 0 ;e < 20 ;e + + ) { System . out . print (map[i][e]); } System . out . println (); } } public void run() { set(); System . out . println ( "**Bear의 fish 먹기 게임을 시작합니다.**" ); int fish_move = 0 ; int total_move = 0 ; printMap(); boolean flag = true ; while (flag) { bear.move(); int r = ( int )(Math.random() * 2 ); //0이면 움직이고 1이면 가만히 있습니다. if (total_move = = 5 ) { fish_move = 0 ; total_move = 0 ; } if (r = = 0 & & fish_move < 2 ) { System . out . println (r); printMap(); fish.move(); fish_move + = 1 ; total_move + = 1 ; } else if (r = = 1 & & total_move > 3 & & fish_move < 2 ) { fish.move(); printMap(); fish_move + = 1 ; total_move + = 1 ; } else { printMap(); total_move + = 1 ; } //게임 종료조건 if (bear.collide(fish)) { printMap(); System . out . println ( "Bear Wins!!" ); flag = false ; } } } } Colored by Color Scripter cs 1. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 package RealQuestion; public class Q01 { public static void main( String [] args) { ColorTV myTV = new ColorTV( 32 , 1024 ); myTV.printProperty(); } } class TV{ private int size; public TV( int size) { this .size = size; } protected int getSize() { return size; } } class ColorTV extends TV{ private int numColor; public ColorTV( int size, int numColor) { super (size); this .numColor = numColor; } public void printProperty() { System . out . println (getSize() + "인치 " + numColor + "컬러" ); } //2번에서 컬러수 리턴할때 쓰입니다. public int getColor() { return numColor; } } Colored by Color Scripter cs 2. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 package RealQuestion; public class Q02 { public static void main( String [] args) { IPTV iptv = new IPTV( "192.1.1.2" , 32 , 2048 ); iptv.printProperty(); } } class IPTV extends ColorTV{ private String IP; public IPTV( String IP, int size, int numColor) { super (size, numColor); this .IP = IP; } @Override public void printProperty() { System . out . println ( "나의 IPTV는 " + IP + " 주소의 " + getSize() + "인치 " + getColor() + "컬러" ); //앞의 ColorTV 클래스의 printProperty를 출력하는 방법도 있습니다! 그게 더 깔끔하겠네요. } } Colored by Color Scripter cs 3. 4. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 public class Q04 { public static void main( String [] args) { Km2Mile toMile = new Km2Mile( 1. 6 ); toMile.run(); } } class Km2Mile extends Converter{ public Km2Mile( double d) { this .ration = d; } @Override protected double convert( double src) { src = src / ration; return src; } @Override protected String getSrcString() { return "Km" ; } @Override protected String getDestString() { // TODO Auto-generated method stub return "mile" ; } } Colored by Color Scripter cs 5. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 package RealQ; public class Q05 { 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 + "입니다." ); } } class ColorPoint extends Point{ private String Color; public ColorPoint( int x, int y, String Color) { super (x,y); this .Color = Color; } public void setXY( int x, int y) { move(x,y); } public void setColor( String Col) { Color = Col; } public String getColor() { return Color; } public String toString () { String str = getColor() + "색의 (" + getX() + "," + getY() + ")의 점" ; return str; } } Colored by Color Scripter cs 6. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 package RealQ; public class Q06 { public static void main( String [] args) { // TODO Auto-generated method stub ColorPoint_two zeroPoint = new ColorPoint_two(); System . out . println (zeroPoint. toString () + "입니다." ); ColorPoint_two cp = new ColorPoint_two( 10 , 10 ); cp.setXY( 5 , 5 ); cp.setColor( "RED" ); System . out . println (cp. toString () + "입니다." ); } } class ColorPoint_two extends Point{ String Color; public ColorPoint_two() { super ( 0 , 0 ); Color = "BLACK" ; } public ColorPoint_two( int x, int y) { super (x, y); Color = "BLACK" ; } public void setXY( int a, int b) { move(a,b); } public void setColor( String src) { Color = src; } public String getColor() { return Color; } public String toString () { String str = getColor() + "색의 (" + getX() + "," + getY() + ")의 점" ; return str; } } Colored by Color Scripter cs 7. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package RealQ; public class Q07 { public static void main( String [] args) { Point3D p = new Point3D( 1 , 2 , 3 ); System . out . println (p. toString () + "입니다." ); p.moveUp(); //z축으로 위쪽 이동 System . out . println (p. toString () + "입니다." ); p.moveDown(); p.move( 10 , 10 ); System . out . println (p. toString () + "입니다." ); p.move( 100 , 200 , 300 ); System . out . println (p. toString () + "입니다." ); } } class Point3D extends Point{ private int z; public Point3D( int x, int y, int z) { super (x, y); this .z = z; // TODO Auto-generated constructor stub } public void moveUp() { z + + ; } public void moveDown() { z - - ; } public void move( int x, int y, int z) { move(x,y); this .z = z; } public int getZ() { return z; } public String toString () { String str = "(" + getX() + "," + getY() + "," + getZ() + ")의 점" ; return str; } } Colored by Color Scripter cs 8. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 package RealQ; public class Q08 { public static void main( String [] args) { // TODO Auto-generated method stub PositivePoint p = new PositivePoint(); p.move( 10 , 10 ); System . out . println (p. toString ()); //"입니다"를 toString에 넣겠습니다.왜 나눠놨을까요? p.move( - 5 , 5 ); System . out . println (p. toString ()); PositivePoint p2 = new PositivePoint( - 10 , - 10 ); System . out . println (p2. toString ()); } } class PositivePoint extends Point{ int a, b; public PositivePoint() { super ( 0 , 0 ); } public PositivePoint( int x, int y) { super (x, y); if (x < 0 | | y < 0 ) { move( 0 , 0 ); } } @Override public void move( int x, int y) { if (x > = 0 & & y > = 0 ) { super .move(x, y); } else { //문제랑 똑같이 하고 싶으면 이부분을 빼면 됩니다! System . out . println ( “음수로는 못가요!” ); } } public String toString () { String str = “(” + getX() + “,” + getY() + “)의 점입니다.” ; return str; } } Colored by Color Scripter cs

9.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 package RealQ; import java.util. Scanner ; public class Q09 { public static void main( String [] args) { Scanner sc = new Scanner ( System . in ); System . out . print ( “총 스택 저장 공간의 크기 입력 >> ” ); int len = sc.nextInt(); StringStack st = new StringStack(len); while ( true ) { System . out . print ( “문자열 입력 >> ” ); String val = sc.next(); if (val.contentEquals( “그만” )) { break ; } if ( ! st.push(val)) { System . out . println ( “스택이 곽차서 푸시 불가!” ); } } System . out . print ( “스택에 저장된 모든 문자열 팝 : ” ); for ( int i = 0 ; i < st. length (); i + + ) { System . out . print (st.pop() + " " ); } } } class StringStack implements Stack{ private int top; private String [] stack; private int len; //스택 크기 private int poss; //지금 들어찬게 몇번짼지 StringStack( int len){ this .len = len; stack = new String [len]; //스택 크기만큼 배열 생성 top = - 1 ; //지금 꼭대기는 -1; poss = 0 ; } @Override public int length () { // TODO Auto-generated method stub return poss; // 지금 들어차있는 수 } @Override public int capacity() { // TODO Auto-generated method stub return len; } @Override public String pop() { //스택의 top에 실수 저장 // TODO Auto-generated method stub if (top = = - 1 ) { System . out . println ( "스택이 비어있습니다." ); } String s = stack[top]; top - - ; //pop해서 배열에 있는 값을 뻈으니 (실제로는 들어있고 삭제하지 않았습니다. top이 가리키는 변수가 하나 줄어들뿐) return s; } @Override public boolean push( String val) { // 스택의 top에 저장된 실수 리턴 if (poss = = len) { return false ; } else { top + + ; poss + + ; //저장 됐으니까 poss 올림 stack[top] = val; return true ; } } } Colored by Color Scripter cs 10. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 package RealQ; public class Q10 { public static void main( String [] args) { Dictionary dic = new Dictionary( 10 ); dic.put( "황기태" , "자바" ); dic.put( "이재문" , "파이선" ); dic.put( "이재문" , "C++" ); System . out . println ( "이재문의 값은 " + dic.get( "이재문" )); System . out . println ( "황기태의 값은 " + dic.get( "황기태" )); dic.delete( "황기태" ); System . out . println ( "황기태의 값은 " + dic.get( "황기태" )); } } class Dictionary extends PairMap{ private int len; private int key_num; //key랑 vlaue 저장할 순번 입니다. private String value; //get, delete함수할때 return할때 쓸 변수. public Dictionary( int len) { this .len = len; super .keyArray = new String [len]; super .valueArray = new String [len]; key_num = - 1 ; //아무것도 없을떈 -1 } @Override String get( String key) { for ( int i = 0 ; i < len; i + + ) { if (key. equals (keyArray[i])) { value = valueArray[i]; break ; } if (i = = len - 1 ) { value = "null" ; } } return value; } @Override void put( String key, String value) { for ( int i = 0 ; i < len;i + + ) { if (key. equals (keyArray[i])) { valueArray[i] = value; break ; } if (i = = len - 1 ) { key_num + + ; keyArray[key_num] = key; valueArray[key_num] = value; } } } @Override String delete( String key) { for ( int i = 0 ; i < len;i + + ) { if (key. equals (keyArray[i])) { value = valueArray[i]; valueArray[i] = "null" ; keyArray[i] = "null" ; break ; } } return value; } @Override int length () { return key_num + 1 ; } } Colored by Color Scripter cs 11. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 package RealQ; import java.util. Scanner ; public class Q11 { public static void main( String [] args) { Scanner sc = new Scanner ( System . in ); System . out . print ( "두 정수와 연산자를 입력하시오>>” ); int a = sc.nextInt(); int b = sc.nextInt(); String cal = sc.next(); switch (cal) { 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 ; default : System . out . print ( “제대로 입력하세요.” ); } } } abstract class Calc{ int a; int b; public void setValue( int a, int b) { this .a = a; this .b = b; } abstract int calculate(); //계산결과 리턴해야하니까 int를 반환형으로 했습니다. } class Add extends Calc{ public int calculate() { return a + b; } } class Sub extends Calc{ public int calculate() { return a – b; } } class Mul extends Calc{ public int calculate() { return a * b; } } class Div extends Calc{ public int calculate() { if (b = = 0 ) { System . out . println ( “0으로는 나눌 수 없습니다.” ); return – 1 ; } return a / b; } } Colored by Color Scripter cs

12.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 package RealQ; import java.util. Scanner ; public class Q12 { public static void main( String [] args) { GraphicEditor ge = new GraphicEditor(); ge.run(); } } class GraphicEditor{ Scanner sc = new Scanner ( System . in ); private Shape start,end; private int num; public void run() { System . out . println ( “그래픽 에디터 YUNO를 실행합니다.” ); boolean point = true ; while (point) { System . out . print ( “삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>” ); num = sc.nextInt(); switch (num) { case 1 : System . out . print ( “Line(1), Rect(2), Circle(3)>>” ); int a = sc.nextInt(); insert(a); break ; case 2 : System . out . print ( “삭제할 도형의 위치>>” ); int loc = sc.nextInt(); delete(loc); break ; case 3 : Shape f = start; while ( true ) { if (start = = null ) { //아무것도 없을떄 System . out . println ( “아무것도 없어요” ); break ; } if (start. equals (end)) { //하나만 있을때 start.draw(); break ; } else { f.draw(); f = f.getNext(); if (f. equals (end)) { f.draw(); break ; } } } break ; case 4 : System . out . println ( “yuno를 종료합니다.” ); point = false ; } } } public void delete( int loc) { Shape cur = start; Shape next = start; int i = 1 ; for (; i < loc; i + + ) { cur = next; next = cur.getNext(); if (cur = = null ) { System . out . println ( "삭제할 수 없습니다(입력수보다 노드 적음)" ); } } if (i = = loc) { cur.setNext(next.getNext()); end = cur; } else { cur.setNext(cur.getNext()); } } public void insert( int a) { Shape obj; switch (a) { case 1 : if (start = = null ) { obj = new Line(); start = obj; end = obj; } else { obj = new Line(); end.setNext(obj); end = obj; } break ; case 2 : if (start = = null ) { obj = new Rect(); start = obj; end = obj; } else { obj = new Rect(); end.setNext(obj); end = obj; } break ; case 3 : if (start = = null ) { obj = new Circle(); start = obj; end = obj; } else { obj = new Circle(); end.setNext(obj); end = obj; } break ; } } } abstract class Shape{ private Shape next; public Shape() {next = null ;} public void setNext(Shape obj) { next = obj; } public Shape getNext() { return next; } public abstract 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" ); } } Colored by Color Scripter cs 13. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 package RealQ; public class Q13 { public static void main( String [] args) { Shape donut = new Circle( 10 ); donut.redraw(); System . out . println ( "면적은 " + donut.getArea()); } } class Circle implements Shape{ private int r; public Circle( int r) { this .r = r; } @Override public void draw() { System . out . println ( " 반지름이 " + r + "인 원입니다." ); } @Override public double getArea() { return r * r * PI; } } interface Shape{ final double PI = 3. 14 ; void draw(); double getArea(); default public void redraw() { System . out . print ( "--- 다시 그립니다." ); draw(); } } Colored by Color Scripter cs 14. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 package RealQ; public class Q14 { public static void main( String [] args) { Shape [] list = new Shape[ 3 ]; list[ 0 ] = new Circle( 10 ); list[ 1 ] = new Oval( 20 , 30 ); list[ 2 ] = new Rect( 10 , 40 ); for ( int i = 0 ; i < list. length ; i + + ) { list[i].redraw(); } for ( int i = 0 ; i < list. length ; i + + ) { System . out . println ( "면적은 " + list[i].getArea()); } } } class Rect implements Shape{ private int a,b; public Rect( int a, int b) { this .a = a; this .b = b; } @Override public void draw() { System . out . println ( " " + a + "x" + b + "크기의 사각형 입니다." ); } @Override public double getArea() { // TODO Auto-generated method stub return a * b; } } class Oval implements Shape{ private int a,b; public Oval( int a, int b) { this .a = a; this .b = b; } @Override public void draw() { // TODO Auto-generated method stub System . out . println ( " " + a + "x" + b + "에 내접하는 타원입니다." ); } @Override public double getArea() { // TODO Auto-generated method stub return PI * a * b; } } Colored by Color Scripter cs

명품 JAVA Programming 5장 실습문제 9번, 10번, 11번

9번. 다음 Stack 인터페이스를 상속받아 실수를 저장하는 StringStack 클래스를 구현하라.

1 2 3 4 5 6 interface Stack{ int length (); //현재 스택에 저장된 개수 리턴 int capacity(); //스택의 전체 저장 가능한 개수 리턴 String pop(); //스택의 촙에 실수 저장 boolean push( String val); //스택의 촙에 저장된 실수 리턴 } Colored by Color Scripter cs

그리고 다음 실행 사례와 같이 작동하도록 StackApp 클래스에 main()메소드를 작성하라.

[실행결과]

총 스택의 저장 공간의 크기 입력>>3

문자열 입력>>hello

문자열 입력>>sunny

문자열 입력>>smile

문자열 입력>>happy

스택이 꽉 차서 푸시 불가!

문자열 입력>>그만

스택에 저장된 모든 문자열 팝 : smile sunny hello

[풀이]

StringStack 클래스

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 class StringStack implements Stack { int num; //스택에 저장 가능한 개수 num int length ; //현재 스택에 저장된 개수 length String [] stack; StringStack( int num){ this .num = num; this . length = 0 ; stack = new String [num]; } @Override public int length () { // TODO Auto-generated method stub return length ; } @Override public int capacity() { // TODO Auto-generated method stub return num; } @Override public String pop() { // TODO Auto-generated method stub if (num < - 1 ) return null ; length - - ; return stack[ length ]; } @Override public boolean push( String val) { // TODO Auto-generated method stub if ( length < num) { stack[ length ] = val; length + + ; return true ; } return false ; } } Colored by Color Scripter cs StackApp 클래스 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class StackApp { public static void main( String [] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner ( System . in ); System . out . print ( "총 스택의 저장 공간의 크기 입력>>” ); int num = scanner.nextInt(); StringStack sst = new StringStack(num); while ( true ) { System . out . print ( “문자열 입력>>” ); String val = scanner.next(); if (val. equals ( “그만” )) break ; if ( ! sst.push(val)) { System . out . println ( “스택이 꽉 차서 푸시 불가!” ); } } System . out . print ( “스택에 저장된 모든 문자열 팝 : ” ); for ( int i = 0 ; i < num; i + + ) { String s = sst.pop(); System . out . print (s + " " ); } Colored by Color Scripter cs 10. 다음은 키와 값을 하나의 아이템으로 저장하고 검색 수정이 가능한 추상 클래스가 있다. 1 2 3 4 5 6 7 8 9 10 11 package practice5_10; abstract public class PairMap { protected String KeyArray[]; protected String valueArray[]; abstract String get( String key); abstract void put( String key, String value); abstract String delete( String key); abstract int length (); } Colored by Color Scripter cs PairMap을 상속하는 Dictionary 클래스를 구현하고, 이를 다음과 같이 활용하는 main() 메소드를 가진 클래스 DictionaryApp도 작성하라. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package practice5_10; public class DictionaryApp { public static void main( String [] args) { // TODO Auto-generated method stub Dictionary dic = new Dictionary( 10 ); dic.put( "황기태" , "자바" ); dic.put( "이재문" , "파이선" ); dic.put( "이재문" , "C++" ); System . out . println ( "이재문은 값은 " + dic.get( "이재문" )); System . out . println ( "황기태의 값은 " + dic.get( "황기태" )); dic.delete( "황기태" ); System . out . println ( "황기태의 값은 " + dic.get( "황기태" )); } } Colored by Color Scripter cs [실행결과] 이재문은 값은 C++ 황기태의 값은 자바 황기태의 값은 null [풀이] Dictionary 클래스 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 public class Dictionary extends PairMap{ int length ; String key; String value; String KeyArray[]; String valueArray[]; int n = 0 ; Dictionary( int length ){ this . length = length ; KeyArray = new String [ length ]; valueArray = new String [ length ]; this .n = 0 ; } @Override String get( String key) { // TODO Auto-generated method stub if (key. equals (KeyArray[ 0 ])) return valueArray[ 0 ]; if (key. equals (KeyArray[ 1 ])) return valueArray[ 1 ]; if (key. equals (KeyArray[ 2 ])) return valueArray[ 2 ]; else return null ; } @Override void put( String key, String value) { // TODO Auto-generated method stub for ( int i = 0 ; i < length ;i + + ) if (key. equals (KeyArray[i])) { KeyArray[i] = key; valueArray[i] = value;} KeyArray[n] = key; valueArray[n] = value; n + + ; } @Override String delete( String key) { // TODO Auto-generated method stub for ( int i = 0 ; i < length ; i + + ) if (key. equals (KeyArray[i])) { String s = KeyArray[i]; KeyArray[i] = null ; return s;} return null ; } @Override int length () { // TODO Auto-generated method stub return length ; } } Colored by Color Scripter cs 11. 철수 학생은 다음 3개의 필드와 메소드를 가진 4개의 클래스 Add, Sub, Mul, Div를 작성하려고 한다(4장 실습문제 11 참고). - int 타입의 a, b 필드: 2개의 피연산자 - void setValue(int a, int b): 피연산자 값을 객체 내에 저장한다. - int calculate(): 클래스의 목적에 맞는 연산을 실행하고 결과를 리턴한다. 곰곰 생각해보니, Add, Sub, Mul, Div 클래스에 공통된 필드와 메소드가 존재하므로 새로운 추상 클래스 Calc를 작성하고 Calc를 상속받아 만들면 되겠다고 생각했다. 그리고 main() 메소드에서 다음 실행 사례와 같이 2개의 정수와 연산자를 입력받은 후, Add, Sub, Mul, Div 중에서 이 연산을 처리할 수 있는 객체를 생성하고 setValue() 와 calculate()를 호출하여 그 결과 값을 화면에 출력하면 된다고 생각하였다. 철수처럼 프로그램을 작성하라. [실행결과] 두 정수와 연산자를 입력하시오 >> 5 7 +

12

[풀이]

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 package practice5_11; public abstract class Calc { //추상 클래스Calc를 생성 int a; int b; void setValue() {}; void calculate() {}; } package practice5_11; public class Add { int a; int b; void setValue( int a, int b) {// 추상메소드에 오버라이딩을 합니다. this .a = a; this .b = b; } int claculate() { return a + b; } } package practice5_11; public class Sub { int a; int b; void setValue( int a, int b) { this .a = a; this .b = b; } int claculate() { return a – b; } } package practice5_11; public class Mul { int a; int b; void setValue( int a, int b) { this .a = a; this .b = b; } int claculate() { return a * b; } } package practice5_11; public class Div { int a; int b; void setValue( int a, int b) { this .a = a; this .b = b; } int claculate() { return a / b; } } package practice5_11; import java.util. Scanner ; public class Cal { public static void main( String [] args) { // TODO Auto-generated method stub int a,b; String c; Scanner scanner = new Scanner ( System . in ); System . out . print ( “두 정수와 연산자를 입력하시오>>” ); a = scanner.nextInt(); b = scanner.nextInt(); c = scanner.next(); switch (c) { //switch문을 써서 구별해 줍니다. case “+” : Add add = new Add(); add .setValue(a, b); System . out . println ( add .claculate()); break ; //switch 문에서는 반드시 break를 써야 합니다. 그렇지 않으면 한바퀴 돕니다. case “-” : Sub sub = new Sub(); sub.setValue(a, b); System . out . println (sub.claculate()); break ; case “*” : Mul mul = new Mul(); mul.setValue(a, b); System . out . println (mul.claculate()); break ; case “/” : Div div = new Div(); div.setValue(a, b); System . out . println (div.claculate()); break ; default : System . out . println ( “그만” ); } } } Colored by Color Scripter cs

728×90

키워드에 대한 정보 명품 자바 프로그래밍 5 장 실습 문제

다음은 Bing에서 명품 자바 프로그래밍 5 장 실습 문제 주제에 대한 검색 결과입니다. 필요한 경우 더 읽을 수 있습니다.

이 기사는 인터넷의 다양한 출처에서 편집되었습니다. 이 기사가 유용했기를 바랍니다. 이 기사가 유용하다고 생각되면 공유하십시오. 매우 감사합니다!

사람들이 주제에 대해 자주 검색하는 키워드 자바프로그래밍실습 5장

  • 동영상
  • 공유
  • 카메라폰
  • 동영상폰
  • 무료
  • 올리기

자바프로그래밍실습 #5장


YouTube에서 명품 자바 프로그래밍 5 장 실습 문제 주제의 다른 동영상 보기

주제에 대한 기사를 시청해 주셔서 감사합니다 자바프로그래밍실습 5장 | 명품 자바 프로그래밍 5 장 실습 문제, 이 기사가 유용하다고 생각되면 공유하십시오, 매우 감사합니다.

See also  영어 토론 주제 | Ytn·한국외대 주최 고등학교 영어토론대회 / Ytn 사이언스 모든 답변

Leave a Reply

Your email address will not be published. Required fields are marked *