일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- SQL 중복제거
- strip_tags #html태그제거 #PHP strip_tags
- DATE_ADD()
- 배열관련함수
- explode #선택제거 #PHP explode
- DATEDIFF()
- CURDATE()
- DATE_SUB()
- trim #공백 제거 #PHP trim()
- PDO #DB접속
- PHP달력관련함수
- apt-get #apt-get 옵션 #apt-get options
- 가상화
- HAVING 절
- 함수정의확인
- Now()
- Java 및 이클립스 설치
- JSTL
- BufferedReader #BufferedWriter
- apt #apt 명령어 #apt-get명령어
- 영카트 #테스트메일
- 이클립스 설치
- serializeObject
- MySQL 날짜 관련 함수
- Java환경변수 설정
- CURTIME()
- php5.x
- DATE_FORMAT()
- sql용어
- db접속
- Today
- Total
M
4장 실습문제 본문
1. 자바 클래스를 작성하는 연습을 해보자. 다음 main() 메소드를 실행하였을 때 예시와 같이 출력되도록 TV 클래스를 작성하라.
class TV {
private String manufacturer;
private int year;
private int size;
TV() {}
TV(String manufacturer, int year, int size) {
this.manufacturer = manufacturer;
this.year = year;
this.size = size;
}
public void show() {
System.out.println(this.manufacturer +"에서 만든 "+ this.year +"년형 " + this.size + "인치 TV");
}
}
public class Problem04_1 {
public static void main(String[] args) {
TV myTV = new TV("LG", 2017, 32);
myTV.show();
}
}
2. Grade 클래스를 작성해보자. 3 과목의 점수를 입력받아 Grade 객체를 생성하고 성적평균을 출력하는 main()과 실행 예시는 다음과 같다.
import java.util.Scanner;
class Grade {
private int math;
private int science;
private int english;
Grade() {}
Grade(int math, int science, int english) {
this.math = math;
this.science = science;
this.english = english;
}
public int average() {
return (this.math + this.science + this.english) / 3;
}
}
public class Problem04_2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("수학, 과학, 영어 순으로 3개의 점수 입력>>");
int math = sc.nextInt();
int science = sc.nextInt();
int english = sc.nextInt();
Grade me = new Grade(math, science, english);
System.out.println("평균은 " + me.average());
sc.close();
}
}
3. 노래 한 곡을 나타내는 Song 클래스를 작성하라.
class Song {
private String title;
private String artist;
private int year;
private String county;
Song() {}
Song(String title, String artist, int year, String county) {
this.title = title;
this.artist = artist;
this.year = year;
this.county = county;
}
public void show() {
System.out.println(this.year +"년 "+ this.county +"국적의 "+ this.artist +"가 부른 "+ this.title);
}
}
public class Problem04_3 {
public static void main(String[] args) {
Song song = new Song("Dancing Queen","ABBA",1978,"스웨덴");
song.show();
}
}
4. 다음 멤버를 가지고 직사각형을 표현하는 Rectangle 클래스를 작성하라.
class Rectangle {
private int x;
private int y;
private int width;
private int height;
Rectangle() {}
Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public int square() {
return this.width * this.height;
}
public boolean contains(Rectangle obj) {
if(this.x < obj.x && this.y < obj.y && (this.x + this.width) > (obj.x + obj.width) && (this.y + this.height) > (obj.y + obj.height))
return true;
else
return false;
}
public void show() {
System.out.printf("(%d, %d)에서 크기가 %dx%d인 사각형\n", this.x, this.y, this.width, this.height);
}
}
public class Problem04_4 {
public static void main(String[] args) {
Rectangle r = new Rectangle(2, 2, 8, 7);
Rectangle s = new Rectangle(5, 5, 6, 6);
Rectangle t = new Rectangle(1, 1, 10, 10);
r.show();
System.out.println("s의 면적은 " + s.square());
if(t.contains(r)) System.out.println("t는 r을 포함합니다.");
if(t.contains(s)) System.out.println("t는 s을 포함합니다.");
}
}
5. 다음 설명대로 Circle 클래스와 CircleManager 클래스를 완성하라.
import java.util.Scanner;
class Circle {
private double x, y;
private int radius;
public Circle(double x, double y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
public void show() {
System.out.println("("+ this.x +","+ this.y +")"+ this.radius);
}
}
public CircleManager {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Circle c [] = new Circle[3];
for(int i=0; i<c.length; i++) {
System.out.print("x, y, radius >>");
double x = scanner.nextDouble();
double y = scanner.nextDouble();
int radius = scanner.nextInt();
c[i] = new Circle(x, y, radius);
}
for(int i=0; i<c.length; i++) c[i].show();
scanner.close();
}
}
6. 앞의 5번 문제는 정답이 공개되어 있다. 이 정답을 참고하여 Circle 클래스와 CircleManager 클래스를 수정하여 다음 실행 결과처럼 되게 하라.
import java.util.Scanner;
class Circle {
private double x, y;
private int radius;
public Circle(double x, double y, int radius) {
this.x = x;
this.y = y;
this.radius = radius;
}
public int getRadius() {
return this.radius;
}
public void show() {
System.out.println("("+ this.x +","+ this.y +")"+ this.radius);
}
}
public class CircleManager {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Circle c[] = new Circle[3];
for(int i=0; i<c.length; i++) {
System.out.print("x, y, radius >>");
double x = scanner.nextDouble();
double y = scanner.nextDouble();
int radius = scanner.nextInt();
c[i] = new Circle(x, y, radius);
}
int num = 0;
for(int i=1; i<c.length; i++) {
if(c[num].getRadius() < c[i].getRadius() ) {
num = i;
}
}
System.out.print("가장 면적이 큰 원은 ");
c[num].show();
scanner.close();
}
}
7. 하루의 할 일을 표현하는 클래스 Day는 다음과 같다. 한 달의 할 일을 표현하는 MonthSchedule 클래스를 작성하라.
MonthSchedule 클래스에는 Day 객체 배열과 적절한 필드, 메소드를 작성하고 실행 예시처럼 입력, 보기, 끝내기 등의 3개의 기능을 작성하라.
import java.util.Scanner;
class Day {
private String work;
public void set(String work) { this.work = work; }
public String get() { return work; }
public void show() {
if(work == null) System.out.println("없습니다.");
else System.out.println(work + "입니다.");
}
}
public class MonthSchedule {
Scanner sc;
private Day[] day;
MonthSchedule(int day) {
this.sc = new Scanner(System.in);
this.day = new Day[day];
}
public void input() {
System.out.print("날짜(1~30)?");
int date = sc.nextInt();
date--;
System.out.print("할일(빈칸없이입력)?");
String work = sc.next();
this.day[date].set(work);
}
public void view() {
System.out.print("날짜(1~30)?");
int date = sc.nextInt();
System.out.print(date +"일의 할 일은 ");
date--;
this.day[date].show();
}
public void finish() {
System.out.println("프로그램을 종료합니다.");
sc.close();
}
public void run() {
for(int i = 0; i < this.day.length; i++) {
this.day[i] = new Day();
}
System.out.println("이번달 스케줄 관리 프로그램.");
while(true) {
System.out.print("할일(입력:1, 보기:2, 끝내기:3) >>");
int n = sc.nextInt();
switch(n) {
case 1: input(); break;
case 2: view(); break;
case 3: finish(); return;
default: System.out.println("(입력:1, 보기:2, 끝내기:3) 중에서 입력해주세요.");
}
}
}
public static void main(String[] args) {
MonthSchedule april = new MonthSchedule(30);
april.run();
}
}
8. 이름(name), 전화번호(tel) 필드와 생성자 등을 가진 Phone 클래스를 작성하고, 실행 예시와 같이 작동하는 PhoneBook 클래스를 작성하라.
class Phone {
private String name;
private String tel;
Phone(String name, String tel) {
this.name = name;
this.tel = tel;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setTel(String tel) {
this.tel = tel;
}
public String getTel() {
return this.tel;
}
public void show() {
System.out.printf("%s의 번호는 %s 입니다.\n", this.name, this.tel);
}
}
public class PhoneBook {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Phone[] phone;
int i;
System.out.print("인원수>>");
int n = sc.nextInt();
phone = new Phone[n];
for(i = 0; i < phone.length; i++) {
System.out.print("이름과 전화번호(이름과 번호는 빈 칸없이 입력)>>");
String name = sc.next();
String tel = sc.next();
phone[i] = new Phone(name, tel);
}
System.out.println("저장되었습니다...");
while(true) {
System.out.print("검색할 이름>>");
String name = sc.next();
if(name.equals("그만") == true) break;
for(i = 0; i < phone.length; i++) {
if(name.equals(phone[i].getName()) == true) {
phone[i].show();
break;
}
}
if(i == phone.length) System.out.println(name +" 이 없습니다.");
}
sc.close();
}
}
9. 다음 2개의 static 가진 ArrayUtil 클래스를 만들어보자. 다음 코드의 실행 결과를 참고하여 concat()와 print()를 작성하여 ArrayUtil 클래스를 완성하라.
class ArrayUtil {
public static int[] concat(int[] a, int[] b) {
int[] temp = new int[a.length + b.length];
int i = 0;
for(; i<a.length; i++) {
temp[i] = a[i];
}
for(; i<temp.length; i++) {
temp[i] = b[i - a.length];
}
return temp;
}
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);
}
}
10. 다음과 같은 Dictionary 클래스가 있다. 실행 결과와 같이 작동하도록 Dictionary 클래스의 kor2Eng() 메소드와 DicApp 클래스를 작성하라.
import java.util.Scanner;
class Dictionary {
static String str;
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(kor[i].equals(word) == true) {
if(i % 2 == 0) {
System.out.print(kor[i] +"는 ");
} else {
System.out.print(kor[i] +"은 ");
}
return eng[i];
}
}
return "false";
}
}
public class DicApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String word;
System.out.println("한영 단어 프로그램입니다.");
while(true) {
System.out.print("한글 단어?");
word = sc.next();
if(word.equals("그만")) break;
String eng = Dictionary.kor2Eng(word);
if(eng.equals("false")) {
System.out.println(word +" 저의 사전에 없습니다.");
} else {
System.out.println(eng);
}
}
sc.close();
}
}
11. 다수의 클래스를 만들고 활용하는 연습을 해보자. 더하기(+), 빼기(-), 곱하기(*), 나누기(/)를 수행하는 각 클래스 Add, Sub, Mul, Div를 만들어라. 이들은 모두 다음 필드와 메소드를 가진다.
import java.util.Scanner;
class Add {
private int a;
private int b;
public void setValue(int a, int b) {
this.a = a;
this.b = b;
}
public int calculate() {
return a + b;
}
}
class Sub {
private int a;
private int b;
public void setValue(int a, int b) {
this.a = a;
this.b = b;
}
public int calculate() {
return a - b;
}
}
class Mul {
private int a;
private int b;
public void setValue(int a, int b) {
this.a = a;
this.b = b;
}
public int calculate() {
return a * b;
}
}
class Div {
private int a;
private int b;
public void setValue(int a, int b) {
this.a = a;
this.b = b;
}
public int calculate() {
return a / b;
}
}
public class Calc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("두 정수와 연산자를 입력하시요>>");
int a = sc.nextInt();
int b = sc.nextInt();
char c = sc.next().charAt(0);
int result = 0;
switch(c) {
case '+':
Add add = new Add();
add.setValue(a, b);
result = add.calculate();
break;
case '-':
Sub sub = new Sub();
sub.setValue(a, b);
result = sub.calculate();
break;
case '*':
Mul mul = new Mul();
mul.setValue(a, b);
result = mul.calculate();
break;
case '/':
Div div = new Div();
div.setValue(a, b);
result = div.calculate();
break;
}
System.out.println(result);
sc.close();
}
}
12. 간단한 콘서트 예약 시스템을 만들어보자. 다수의 클래스를 다루고 객체의 배열을 다루기에는 아직 자바 프로그램 개발이 익숙하지 않은 초보자에게 다소 무리가 있을 것이다. 그러나 반드시 넘어야 할 산이다. 이 도전을 통해 산을 넘어갈 수 있는 체력을 키워보자. 예약 시스템의 기능은 다음과 같다.
import java.util.Scanner;
class Reser {
Scanner sc;
int sitCount = 10;
String[] s;
String[] a;
String[] b;
Reser() {
s = new String[sitCount];
a = new String[sitCount];
b = new String[sitCount];
for(int i = 0; i < sitCount; i++) {
s[i] = "---";
a[i] = "---";
b[i] = "---";
}
}
public void inputReser() {
System.out.print("좌석구분 S(1), A(2), B(3)>>");
int sit = sc.nextInt();
switch(sit) {
case 1:
System.out.print("S>>");
printSeat(s);
sitReser(s);
break;
case 2:
System.out.print("A>>");
printSeat(a);
sitReser(a);
break;
case 3:
System.out.print("B>>");
printSeat(b);
sitReser(b);
break;
}
}
public void sitReser(String[] sit) {
System.out.print("이름>>");
String name = sc.next();
System.out.print("번호>>");
int n = sc.nextInt();
sit[n - 1] = name;
}
public void printSeat(String[] sit) {
for(int i = 0; i < sit.length; i++) {
System.out.print(" "+ sit[i]);
}
System.out.println();
}
public void allSeatLists() {
System.out.print("S>>");
printSeat(s);
System.out.print("A>>");
printSeat(a);
System.out.print("B>>");
printSeat(b);
}
public void cancle() {
System.out.print("좌석구분 S(1), A(2), B(3)>>");
int sit = sc.nextInt();
switch(sit) {
case 1:
System.out.print("S>>");
printSeat(s);
cancleSit(s);
break;
case 2:
System.out.print("A>>");
printSeat(a);
cancleSit(a);
break;
case 3:
System.out.print("B>>");
printSeat(b);
cancleSit(b);
break;
}
}
public void cancleSit(String[] sit) {
System.out.print("이름>>");
String name = sc.next();
for(int i = 0; i < sit.length; i++) {
if(sit[i].equals(name) == true) {
sit[i] = "---";
}
}
}
public void run() {
sc = new Scanner(System.in);
System.out.println("명품콘서트홀 예약 시스템입니다.");
while(true) {
System.out.print("예약:1 , 조회:2, 취소:3, 끝내기:4>>");
int ch = sc.nextInt();
switch(ch) {
case 1: this.inputReser(); break;
case 2: this.allSeatLists(); break;
case 3:
this.cancle();
break;
case 4:
sc.close();
return;
}
}
}
}
public class Consert {
public static void main(String[] args) {
Reser ConsertReser = new Reser();
ConsertReser.run();
}
}
'Java > 명품 Java Programming' 카테고리의 다른 글
5장 연습문제 (0) | 2022.02.20 |
---|---|
5장 Open Challenge (0) | 2022.02.18 |
4장 연습문제 (0) | 2022.02.07 |
4장 Open Challenge (0) | 2022.02.06 |
3장 실습문제 (0) | 2022.01.29 |