명품 자바 프로그래밍(개정5판) 4장 실습문제 풀이 p. 245-254
public class TV {
private String manufacturer;
private int inch;
private int price;
public TV(String manufacturer, int inch, int price) {
this.manufacturer = manufacturer;
this.inch = inch;
this.price = price;
}
public void show(){
System.out.print(manufacturer + "에서 만든 " + price + "만원짜리의 "+ inch + "인치 TV");
}
public static void main(String[] args) {
TV tv = new TV("Samsung", 50, 300);
tv.show();
}
}
public class Cube {
private int width, height, depth;
public Cube(int width, int height, int depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
public int getVolume() {
return width * height * depth;
}
public void increase(int w, int h, int d) {
this.width += w;
this.height += h;
this.depth += d;
}
public boolean isZero() {
if (width * height * depth == 0)
return true;
else
return false;
}
public static void main(String[] args) {
Cube cube = new Cube(1, 2, 3);
System.out.println("큐브의 부피는 " + cube.getVolume());
cube.increase(1, 2, 3);
System.out.println("큐브의 부피는 " + cube.getVolume());
if (cube.isZero())
System.out.println("큐브의 부피는 0");
else
System.out.println("큐브의 부피는 0이 아님");
}
}
import java.util.Scanner;
public class Grade {
private String name;
private int java, web, os;
public Grade(String name, int java, int web, int os) {
this.name = name;
this.java = java;
this.web = web;
this.os = os;
}
public String getName() {
return name;
}
public int getAverage() {
return (java + web + os) / 3;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("이름, 자바, 웹프로그래밍, 운영체제 순으로 점수 입력>>");
String name = scanner.next();
int java = scanner.nextInt();
int web = scanner.nextInt();
int os = scanner.nextInt();
Grade st = new Grade(name, java, web, os);
System.out.print(st.getName() + "의 평균은 " + st.getAverage());
scanner.close();
}
}
public class Average {
private int[] arr;
private int index;
public Average() {
arr = new int[10];
index = 0;
}
public void put(int x) {
arr[index] = x;
index++;
}
public void showAll() {
System.out.println("***** 저장된 데이터 모두 출력 *****");
for(int i=0; i<index; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public double getAvg() {
if (index == 0) {
return 0;
}
int sum = 0;
for(int i=0; i < index; i++) {
sum += arr[i];
}
return (double) sum / index;
}
public static void main(String[] args) {
Average avg = new Average();
avg.put(10);
avg.put(15);
avg.put(100);
avg.showAll();
System.out.print("평균은 " + avg.getAvg());
}
}
public class Song {
private String title, singer, lang;
private int year;
public Song(String title, String singer, int year, String lang){
this.title = title;
this.singer = singer;
this.year = year;
this.lang = lang;
}
public void show() {
System.out.print(year+"년 " + lang+"의 " + singer+"가 부른 ");
System.out.println(title);
}
public static void main(String[] args) {
Song song1 = new Song("가로수 그늘 아래 서면", "이문세", 1988, "한국");
song1.show();
}
}
public class Rectangle {
int x, y, width, height;
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public boolean isSquare() {
return (width==height);
}
public boolean contains(Rectangle r) {
return (r.x >= this.x && r.y >= this.y &&
(r.x + r.width) <= (this.x + this.width) &&
(r.y + r.height) <= (this.y + this.height));
}
public void show() {
System.out.println("(" + x + "," + y + ")에서 크기 " + width + "x" + height + " 사각형");
}
public static void main(String[] args) {
Rectangle a = new Rectangle(3, 3, 6, 6); // (3,3) 점에서 6x6 크기의 사각형
Rectangle b = new Rectangle(4, 4, 2, 3); // (4,4) 점에서 2x3 크기의 사각형
a.show();
if(a.isSquare()) System.out.println("a는 정사각형입니다.");
else System.out.println("a는 직사각형입니다.");
if(a.contains(b)) System.out.println("a는 b를 포함합니다.");
}
}
public class Memo {
private String name, time, content;
public Memo(String name, String time, String content) {
this.name=name;
this.time=time;
this.content=content;
}
public boolean isSameName(Memo m) {
if(name.equals(m.getName())) return true;
else return false;
}
public String getName() {
return this.name;
}
public int length() {
return content.length();
}
public void show() {
System.out.println(name+ ", " + time + " " + content);
}
public static void main(String[] args) {
Memo a = new Memo("유송연", "10:10", "자바 과제 있음");
Memo b = new Memo("박채원", "10:15", "시카고로 어학 연수가요!");
Memo c = new Memo("김경미", "11:30", "사랑하는 사람이 생겼어요.");
a.show();
if(a.isSameName(b)) System.out.println("동일한 사람입니다.");
else System.out.println("다른 사람입니다.");
System.out.println(c.getName() + "가 작성한 메모의 길이는 " + c.length());
}
}
public class Account {
private int balance;
public Account(int balance) {
this.balance = balance;
}
// 입금
public void deposit(int money) {
balance += money;
}
public void deposit(int[] monies) {
for(int i=0; i<monies.length; i++)
balance += monies[i];
}
// 인출
public int withdraw(int money) {
if(balance < money) {
int wmoney = balance;
balance = 0;
return wmoney;
}
else {
balance -= money;
return money;
}
}
// 잔액 반환
public int getBalance() {
return balance;
}
public static void main(String[] args) {
Account a = new Account(100); // 100원을 예금하면서 계좌 생성
a.deposit(5000); // 5000원 예금
System.out.println("잔금은 " + a.getBalance() + "원입니다.");
int bulk[] = {100, 500, 200, 700};
a.deposit(bulk); // bulk[] 배열에 있는 모든 돈 예금
System.out.println("잔금은 " + a.getBalance() + "원입니다.");
int money = 1000; // 인출하고자 하는 금액
int wMoney = a.withdraw(money); // 1000원 인출 시도. wMoney는 실제 인출한 금액
if(wMoney < money)
System.out.println(wMoney + "원만 인출"); //잔금이 1000원보다 작은 경우
else
System.out.println(wMoney + "원 인출"); //잔금이 1000원보다 큰 경우
System.out.println("잔금은 " + a.getBalance() + "원 입니다.");
}
}
// Player 클래스
public class Player {
private String name;
private int score;
public Player(String name) {
this.name = name;
this.score = 0;
}
public void upScore() {
score++;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void show() {
System.out.print(name+ ":" + score + " ");
}
}
// GuessGame 클래스
import java.util.Scanner;
public class GuessGame {
private int numOfPlayer; // 플레이어 수
private Player[] players;
private int[] answers; // 플레이어 입력 저장
private Scanner scanner = new Scanner(System.in);
public GuessGame() {
System.out.println("*** 예측 게임을 시작합니다. ***");
inputPlayers();
playGame();
}
// 플레이어 입력
public void inputPlayers() {
System.out.print("게임에 참여할 선수 수>>");
this.numOfPlayer = scanner.nextInt();
players = new Player[numOfPlayer];
answers = new int[numOfPlayer];
for(int i=0; i<numOfPlayer; i++) {
System.out.print("선수 이름>> ");
players[i] = new Player(scanner.next());
}
}
// 난수 생성
public int generateRandomNumber() {
System.out.println("1~100사이의 숫자가 결정되었습니다. 선수들은 맞추어 보세요.");
int r = (int)(Math.random()*100+1);
return r;
}
// 플레이어 답 입력
public void inputAnswers() {
for(int i=0; i<numOfPlayer; i++) {
System.out.print(players[i].getName() + ">>");
answers[i] = scanner.nextInt();
}
}
// 게임 종료 시 총점 및 승리자 출력
public void showResult() {
int winnerIndex=0;
for(int i=0; i<numOfPlayer; i++) {
if(players[i].getScore() > players[winnerIndex].getScore())
winnerIndex = i;
players[i].show();
}
System.out.println();
System.out.println(players[winnerIndex].getName() + "이 최종 승리하였습니다.");
}
public void playGame() {
while (true) {
int hiddenAnswer = generateRandomNumber();
inputAnswers();
int correctIndex = 0;
int diff = Math.abs(hiddenAnswer-answers[0]);
for (int j = 1; j < numOfPlayer; j++) {
int currentDiff = Math.abs(hiddenAnswer - answers[j]);
if (currentDiff < diff) {
correctIndex = j;
diff = currentDiff;
}
}
// 라운드 결과 출력
players[correctIndex].upScore();
System.out.print("정답은 " + hiddenAnswer + ". ");
System.out.println( players[correctIndex].getName() + "이 이겼습니다. 승점 1점 확보!");
System.out.print("계속하려면 yes 입력>>");
// 게임 종료
if(!scanner.next().equals("yes")) {
showResult();
break;
}
}
scanner.close();
}
public static void main(String[] args) {
GuessGame game = new GuessGame();
}
}
// MonthDiary 클래스
import java.util.Scanner;
public class MonthDiary {
private int year, month;
private DayDiary[] days;
private Scanner scanner = new Scanner(System.in);
public MonthDiary(int year, int month) {
this.year = year;
this.month = month;
switch(month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = new DayDiary[31];
break;
case 4: case 6: case 9: case 11:
days = new DayDiary[30];
break;
case 2:
days = new DayDiary[28];
break;
}
for (int i = 0; i < days.length; i++) {
days[i] = new DayDiary();
}
}
// 1: 기록
public void writeDiary() {
System.out.print("날짜(1~" + days.length +")와 텍스트(빈칸없이 4글자이하)>>");
int day = scanner.nextInt();
String text = scanner.next();
days[day-1].setText(text);
}
// 2: 보기
public void viewDiary() {
for(int i=0; i<days.length; i++) {
System.out.print(days[i].getText() + "\t");
if((i+1) % 7 == 0 ) {
System.out.println();
}
}
System.out.println();
}
public void run() {
System.out.println("***** " + year + "년 " + month + "월 다이어리 *****");
while (true){
System.out.print("기록:1, 보기:2, 종료:3>>");
int choice = scanner.nextInt();
switch (choice) {
case 1:
writeDiary();
break;
case 2:
viewDiary();
break;
case 3:
System.out.println("프로그램을 종료합니다.");
return;
}
}
}
public static void main(String[] args) {
MonthDiary monthDiary = new MonthDiary(2024, 10);
monthDiary.run();
}
}
// DayDiary 클래스
public class DayDiary {
String text;
public DayDiary() {
text = "...";
}
public void setText(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
class ArrayUtil {
// 배열 a와 b를 연결한 새로운 배열 리턴
public static int [] concat(int[] a, int[] b) {
int len = a.length + b.length;
int[] array = new int[len];
for(int i=0; i<a.length; i++) {
array[i] = a[i];
}
for(int j=a.length; j<len; j++) {
array[j] = b[j-a.length];
}
return array;
}
// 배열 a 출력
public static void print(int[] a) {
System.out.print("[ ");
for(int i=0; i<a.length; i++)
System.out.print(a[i] + " ");
System.out.print("]");
}
}
public class StaticEx{
public static void main(String[] args) {
int [] array1 = { 1, 5, 7, 9 };
int [] array2 = { 3, 6, -1, 100, 77 };
int [] array3 = ArrayUtil.concat(array1, array2);
ArrayUtil.print(array3);
}
}
// Dictionary 클래스
public class Dictionary {
private static String[] kor = {"사랑", "아기", "돈", "미래", "희망"};
private static String[] eng = {"love", "baby", "money", "future", "hope"};
public static String kor2Eng(String word) {
for(int i=0; i<kor.length; i++) {
if(word.equals(kor[i])) {
return (word+ "은 " + eng[i]);
}
}
return (word + "는 저의 사전에 없습니다.");
}
}
// DicApp 클래스
import java.util.Scanner;
public class DicApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("한영 단어 검색프로그램입니다.");
while (true) {
System.out.print("한글 단어?");
String search = scanner.next();
if(search.equals("그만")) break;
System.out.println(Dictionary.kor2Eng(search));
}
scanner.close();
}
}
import java.util.Scanner;
class Seats {
private String seat;
public Seats() { seat = "---"; }
public String getSeat() { return seat; }
public void setSeat(String name) { seat = name; }
}
class Section {
Seats seats[] = new Seats[10];
public Section() {
for (int i = 0; i < seats.length; i++)
seats[i] = new Seats();
}
public void show() {
for (int i = 0; i < seats.length; i++) {
System.out.print(seats[i].getSeat() + " ");
}
System.out.println();
}
public void book(String name, int num) {
if (num < 1 || num > seats.length) {
System.out.println("잘못된 좌석 번호입니다.");
return;
}
if (!seats[num - 1].getSeat().equals("---")) {
System.out.println("이미 예약된 좌석입니다.");
return;
}
seats[num - 1].setSeat(name);
}
public void cancel(String name) {
boolean found = false;
for (int i = 0; i < seats.length; i++) {
if (seats[i].getSeat().equals(name)) {
seats[i].setSeat("---");
found = true;
break;
}
}
if (!found) {
System.out.println("예약자 이름을 찾을 수 없습니다.");
}
}
}
public class Concert {
Scanner scanner = new Scanner(System.in);
Section sSection = new Section();
Section aSection = new Section();
Section bSection = new Section();
public void inputBook() {
System.out.print("좌석구분 S(1), A(2), B(3)>>");
int section = scanner.nextInt();
Section selectedSection;
switch (section) {
case 1:
selectedSection = sSection;
System.out.print("S>> ");
break;
case 2:
selectedSection = aSection;
System.out.print("A>> ");
break;
case 3:
selectedSection = bSection;
System.out.print("B>> ");
break;
default:
System.out.println("유효하지 않은 섹션입니다.");
return;
}
selectedSection.show();
System.out.print("이름>>");
String name = scanner.next();
System.out.print("번호>>");
int seatNum = scanner.nextInt();
selectedSection.book(name, seatNum);
}
public void printAllSection() {
System.out.print("S>> ");
sSection.show();
System.out.print("A>> ");
aSection.show();
System.out.print("B>> ");
bSection.show();
System.out.println("<<<조회를 완료하였습니다.>>>");
}
public void cancel() {
System.out.print("좌석구분 S(1), A(2), B(3)>>");
int section = scanner.nextInt();
Section selectedSection;
switch (section) {
case 1: selectedSection = sSection; break;
case 2: selectedSection = aSection; break;
case 3: selectedSection = bSection; break;
default:
System.out.println("유효하지 않은 섹션입니다.");
return;
}
selectedSection.show();
System.out.print("이름>>");
String name = scanner.next();
selectedSection.cancel(name);
}
public static void main(String[] args) {
Concert concert = new Concert();
Scanner scanner = new Scanner(System.in);
System.out.println("명품콘서트홀 예약 시스템입니다.");
while (true) {
System.out.print("예약:1, 조회:2, 취소:3, 끝내기:4>>");
int input = scanner.nextInt();
switch (input) {
case 1:
concert.inputBook();
break;
case 2:
concert.printAllSection();
break;
case 3:
concert.cancel();
break;
case 4:
scanner.close();
return;
default:
System.out.println("유효한 메뉴의 숫자를 입력해주세요.");
break;
}
}
}
}
public class VArray {
int size;
int[] array;
public VArray(int num) {
size = 0;
array = new int[num];
}
public int capacity() {
return array.length;
}
public int size() {
return size;
}
public void add(int n) {
if(size == array.length) {
resize();
}
array[size++] = n;
}
public void insert(int idx, int n) {
if(idx<0 || idx>size) return;
if (size == array.length) {
resize();
}
for (int i = size; i > idx; i--) {
array[i] = array[i - 1];
}
array[idx] = n;
size++;
}
private void resize() {
int newCapacity = array.length * 2;
int[] newArray = new int[newCapacity];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
public void remove(int idx) {
if(idx >= size || idx < 0) return;
for (int i = idx; i < size - 1; i++) {
array[i] = array[i + 1];
}
array[--size] = 0;
}
public void printAll() {
for(int i=0; i<size; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
VArray v = new VArray(5); // 5개의 정수를 저장하는 가변 배열 객체 생성
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
for (int i = 0; i < 7; i++) // 7개 저장
v.add(i); // 배열에 순서대로 정수 i 값 저장
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
v.printAll();
v.insert(3, 100); // 배열의 인덱스 3에 100 삽입
v.insert(5, 200); // 배열의 인덱스 5에 200 삽입
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
v.printAll();
v.remove(10); // 배열의 인덱스 10의 정수 삭제
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
v.printAll();
for (int i = 50; i < 55; i++) // 5개 저장
v.add(i); // 배열에 순서대로 정수 i 값 저장
System.out.println("용량: " + v.capacity() + ", 저장된 개수: " + v.size());
v.printAll();
}
}
개인 풀이이므로 틀린 부분이나 피드백이 있으면 댓글로 남겨주시면 감사하겠습니다!