위 글은 해당 카테고리의 수업 강의 자료(연습문제)를 정리한 것입니다.
손이 가는대로 무지성으로 푼 것도 많아서... 풀었던 문제 정리하면서 객체지향을 이해하는게 나은 것 같아 작성
(연습문제, Pratice03~05 부분)
package com.javaex.problem01;
public class Member {
private String id;
private String name;
private int point;
public Member() {
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
public Member(String id, String name, int point) {
super();
this.id = id;
this.name = name;
this.point = point;
}
public void Draw() {
System.out.println(id+ " "+name+" "+point);
}
@Override
public String toString() {
return "Member [id=" + id + ", name=" + name + ", point=" + point + "]";
}
}
public class MemberApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Member m = new Member("20172829", "지현정", 20172829);
m.Draw();
// m.toString(); XXXX
// toString은 문자열만 반환하므로 System.out.println(변수명.toString())
System.out.println(m.toString());
}
}
public class Base {
public void service(String state) {
if(state.equals("낮"))
day();
else if(state.equals("오후"))
afternoon();
else
night();
}
public void day() {
System.out.println("낮에도 일해");
}
public void night() {
System.out.println("밤에도 일해");
}
public void afternoon() {
System.out.println("오후에도 일해");
}
}
public class BaseApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Base b = new Base();
b.service("낮");
b.service("밤");
b.service("오후");
}
}
public class Print {
public void print(boolean bool) {
System.out.println(bool);
}
public void print(String str) {
System.out.println(str);
}
public void print(int num) {
System.out.println(num);
}
public void print(double number) {
System.out.println(number);
}
}
public class PrintApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Print print = new Print();
print.print(10);
print.print(true);
print.print(5.7);
print.print("홍길동");
}
public class CConverter {
public static double rate;
public static void setRate(double r){
CConverter.rate = r;
}
public static double toDoller(double won){
return won / rate;
}
public static double toKRW(double dollar){
return dollar * rate;
}
}
public class CConverterApp {
public static void main(String[] args) {
double dollar = 1000000;
double won = 100;
CConverter.setRate(1229.40);
System.out.println("백만원은 " + CConverter.toDoller(dollar) + " 달러입니다.");
System.out.println("백달러는"+ CConverter.toKRW(won) + "원입니다.");
}
}
public class StringUtil {
private static String str="";
public static String concatString(String[] strArray) {
for(int i=0; i<strArray.length; i++) {
str+=strArray[i];
}
return str;
}
}
public class StringUtilApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] strArray = {"SuperMan", "BatMan", "SpiderMan"};
String resultStr = StringUtil.concatString(strArray);
System.out.println("결과 문자열:" + resultStr);
}
}
public class Friend {
private String name;
private String hp;
private String school;
public Friend(String name, String hp, String school) {
this.name = name;
this.hp = hp;
this.school = school;
}
//필요한 메소드 작성
public void showInfo(){
System.out.println("이름:"+name+" 핸드폰:"+hp+" 학교:"+school);
}
}
public class FriendApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
Friend[] friendArray = new Friend[3];
Scanner sc = new Scanner(System.in);
System.out.println("친구를 3명 등록해 주세요");
// 친구정보 입력받기
String str1 = sc.nextLine();
String str2 = sc.nextLine();
String str3 = sc.nextLine();
// 입력받은 친구정보를 공백으로 분리 String 클래스에 split(" ") -> array로 넘어감... 명시
String[] arr1 = str1.split(" ");
String[] arr2 = str2.split(" ");
String[] arr3 = str3.split(" ");
// Friend 객체 생성하여 데이터 넣기 -> 생성자 호출 -> 객체 생성
Friend f1 = new Friend(arr1[0], arr1[1], arr1[2]);
Friend f2 = new Friend(arr2[0], arr2[1], arr2[2]);
Friend f3 = new Friend(arr3[0], arr3[1], arr3[2]);
// 배열에 추가하기 ( friendArray <- friend객체 )
friendArray[0] = f1;
friendArray[1] = f2;
friendArray[2] = f3;
// 친구정보 출력
for (int i = 0; i < friendArray.length; i++) {
//친구정보 출력 메소드 호출
friendArray[i].showInfo();
}
sc.close();
}
}
public class Account {
private String accountNo;
private int balance;
//생성자 작성
public Account(String accountNo) {
// TODO Auto-generated constructor stub
System.out.println(accountNo + " 계좌가 개설되었습니다.");
}
//필요한 메소드 작성
public void deposit(int money) {
// TODO Auto-generated method stub
balance += money;
}
public void withdraw(int money) {
balance -= money;
}
public void showBalance() {
// TODO Auto-generated method stub
System.out.println(balance);
}
}
import java.util.Scanner;
public class AccountApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
boolean run = true;
int money;
Account account = new Account("312-89562-123456");
while(run){
System.out.println("");
System.out.println("----------------------------");
System.out.println("1.예금 | 2.출금 | 3.잔고 |4.종료");
System.out.println("----------------------------");
System.out.print("선택>");
int menuNo = sc.nextInt();
switch(menuNo){
case 1:
System.out.print("예금액>");
money = sc.nextInt();
account.deposit(money);
break;
case 2:
System.out.print("출금액>");
money= sc.nextInt();
account.withdraw(money);
break;
case 3:
System.out.print("잔고액>");
account.showBalance();
break;
case 4:
System.out.print("프로그램 종료");
run = false;
break;
default :
System.out.println("다시입력해주세요");
break;
}//switch
}//while
sc.close();
}
}
public class Book {
private int bookNo;
private String title;
private String author;
private int stateCode;
public Book(int bookNo, String title, String author) {
// TODO Auto-generated constructor stub
this.bookNo = bookNo;
this.title = title;
this.author = author;
stateCode = 1;
// this.stateCode = stateCode;
}
public void rent() {
stateCode = 0;
}
public void print() {
if(stateCode == 0)
System.out.println(bookNo+" 책 제목: "+ title+" 저자: "+ author+ " 대여 유무: 대여 중");
else
System.out.println(bookNo+" 책 제목: "+ title+", 저자: "+ author+ ", 대여 유무: 재고 있음");
}
}
import java.util.Scanner;
public class BookShop {
public static void main(String[] args) {
Book[] books = new Book[10];
books[0] = new Book(1, "트와일라잇", "스테파니메이어");
books[1] = new Book(2, "뉴문", "스테파니메이어");
books[2] = new Book(3, "이클립스", "스테파니메이어");
books[3] = new Book(4, "브레이킹던", "스테파니메이어");
books[4] = new Book(5, "아리랑", "조정래");
books[5] = new Book(6, "젊은그들", "김동인");
books[6] = new Book(7, "아프니깐 청춘이다", "김난도");
books[7] = new Book(8, "귀천", "천상병");
books[8] = new Book(9, "태백산맥", "조정래");
books[9] = new Book(10, "풀하우스", "원수연");
System.out.println("*****도서 정보 출력하기******");
displayBookInfo(books);
Scanner scanner = new Scanner(System.in);
System.out.print("대여 하고 싶은 책의 번호를 입력하세요:");
int num = scanner.nextInt();
scanner.close();
// (1) 입력된 번호에 맞는 책을 찾아 대여 되었음(상태코드=0)을 체크 합니다.
books[num-1].rent();
System.out.println("*****도서 정보 출력하기******");
displayBookInfo(books);
}
//(2)전달받은 배열을 모두 출력하는 메소드
private static void displayBookInfo(Book[] books) {
//코드작성
for(int i=0; i<books.length; i++) {
books[i].print();
}
}
}
public class Employee {
private String name;
private int salary;
public Employee() {
}
Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public void getInformation() {
System.out.print("이름:" + name + " 연봉:" + salary);
}
}
public class Depart extends Employee{
private String department;
public Depart(String name, int salary, String department) {
// TODO Auto-generated constructor stub
super(name,salary);
this.department = department;
}
// 상속 받고 메소드 getInformation 오버라이딩
public void getInformation() {
super.getInformation();
System.out.print(" 부서: " + department);
}
}
public class EmployeeApp {
public static void main(String[] args) {
Employee pt = new Depart( "홍길동", 5000, "개발부" );
pt.getInformation();
}
}
public class Phone {
public void execute(String str){
call();
}
private void call(){
System.out.println("통화기능시작");
}
}
public class MusicPhone extends Phone{
public void execute(String str){
if("음악".equals(str)){
playMusic();
}else{
super.execute(str);
}
}
protected void playMusic(){
System.out.println("Mp3플레이어에서 음악재생");
}
}
public class SmartPhone extends MusicPhone {
public void execute(String str){
if("앱".equals(str)){
startApp();
} else if("음악".equals(str)) {
download();
} else{
super.execute(str);
}
}
protected void startApp(){
System.out.println("앱 실행");
}
protected void download() {
System.out.println("다운로드해서 음악재생");
}
}
public class PhoneApp {
public static void main(String[] args) {
Phone phone = new SmartPhone();
phone.execute("앱");
phone.execute("음악");
phone.execute("통화");
}
}
public class BirdApp {
public static void main(String[] args) {
Bird bird01 = new Duck();
bird01.setName("꽥꽥이");
bird01.fly();
bird01.sing();
bird01.showName();
Bird bird02 = new Sparrow();
bird02.setName("짹짹이");
bird02.fly();
bird02.sing();
bird02.showName();
}
}
public abstract class Bird {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public abstract void fly();
public abstract void sing();
public abstract void showName();
}
public class Duck extends Bird {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sing() {
System.out.println("오리("+name+")가 소리내어 웁니다.");
}
public void fly() {
System.out.println("오리("+name+")가 날아 다닙니다.");
}
public void showName() {
System.out.println("오리의 이름은 "+name+"입니다.");
}
}
public class Sparrow extends Bird {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sing() {
System.out.println("참새("+name+")가 소리내어 웁니다.");
}
public void fly() {
System.out.println("참새("+name+")가 날아 다닙니다.");
}
public void showName() {
System.out.println("참새의 이름은 "+name+"입니다.");
}
}
public class SoundApp {
public static void main(String[] args) {
printSound( new Cat() );
printSound( new Dog() );
printSound( new Sparrow() );
printSound( new Duck() );
}
public static void printSound( Soundable soundable ) {
//구현
System.out.println(soundable.sound());
}
}
public interface Soundable {
public String sound();
}
public class Cat implements Soundable{
@Override
public String sound() {
// TODO Auto-generated method stub
return "야옹";
}
}
public class Dog implements Soundable{
@Override
public String sound() {
// TODO Auto-generated method stub
return "멍멍";
}
}
public class Duck implements Soundable{
@Override
public String sound() {
// TODO Auto-generated method stub
return "꽥꽥";
}
}
public class Sparrow implements Soundable {
@Override
public String sound() {
// TODO Auto-generated method stub
return "짹짹";
}
}
public class Add {
private int a;
private int b;
public void setValue(int a, int b) {
// TODO Auto-generated method stub
this.a=a;
this.b=b;
}
int calculate() {
return a+b;
}
}
public class Sub {
private int a;
private int b;
public void setValue(int a, int b) {
// TODO Auto-generated method stub
this.a=a;
this.b=b;
}
int calculate() {
return a-b;
}
}
public class Mul {
private int a;
private int b;
public void setValue() {
}
public void setValue(int a, int b) {
// TODO Auto-generated method stub
this.a=a;
this.b=b;
}
int calculate() {
return a*b;
}
}
public class Div {
private int a;
private int b;
public void setValue(int a, int b) {
// TODO Auto-generated method stub
this.a=a;
this.b=b;
}
int calculate() {
return a/b;
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class CalcApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
while(true) {
System.out.print(">> ");
Scanner sc = new Scanner(System.in);
int a=0;
String sign = "";
int b=0;
try {
a = sc.nextInt();
sign = sc.next();
b = sc.nextInt();
} catch(InputMismatchException e) {
System.out.println("종료합니다..");
break;
}
switch(sign) {
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.println("알 수 없는 연산입니다.");
break;
}
}
}
}
'강의 > KOSTA' 카테고리의 다른 글
[Java] IOStream (Day8) (0) | 2022.03.15 |
---|---|
[Java] Collection Framework (Day7~8) (0) | 2022.03.14 |
[Java] Basic API (Day7) (0) | 2022.03.14 |
[Java] Object Oriented Programming (Day4~6) (0) | 2022.03.14 |
[Java] Introduction to Java (Day1~3) (0) | 2022.03.10 |