danDevlog

Java - day10(배열, 상속, 전화번호 4단계) 본문

Java

Java - day10(배열, 상속, 전화번호 4단계)

단데기이 2022. 2. 28. 11:41
728x90
import java.util.ArrayList;

public class ttt {
	public static void main(String[] args) {
		ArrayList<Book> library = new ArrayList<>();// 이전에 객체 배열 선언과 비슷. 가변 배열.
		// PhoneInfo[] phoneList=new PhoneInfo[100];
		// 객체 배열, 주차 타워와 비슷, 차량은 없는 빈 상태, 모두 null로 초기화, 기본 사이즈 100

		library.add(new Book("태백산맥", "조정래"));
		// ArrayList 요소 1개 추가.
		library.add(new Book("데미안", "헤르만 헤세"));
		library.add(new Book("어떻게 살 것인가", "유시민"));
		library.add(new Book("토지", "박경리"));
		library.add(new Book("어린왕자", "생텍쥐페리"));

		for (int i = 0; i < library.size(); i++) {
			Book b = library.get(i);
			System.out.println(b.toString());
		}
	}
}

class Book {
	String bookName;
	String writer;

	public Book(String bn, String w) {
		bookName = bn;
		writer = w;
	}
	// 메뉴 소스 > 제너레잇 toString
	@Override
	public String toString() {
		return "Book [bookName=" + bookName + ", writer=" + writer + "]";
	}
}
// 상속
public class Inheritance {
	public static void main(String[] args) {
		Customer c = new  Customer();
		VIPCustomer vc = new VIPCustomer();
		
		
		// 기본 타입에서는 자료 저장 공간이 기준.
		// 8byte long >> 4byte int 저장 에러
		// 4byte int >> 8byte long 묵시적 형변환. 자료손실이 발생하지 않음.
		
		Customer c2;
		c2 = vc; // 묵시적 형변환, 부모가 개념적으로 더 큰 자료형
		VIPCustomer vc2;
		vc2 = (VIPCustomer) c;
		// 큰 자료형을 작은 자료형으로 강제 대입을 위해서 명시적 형변환
		
		// 자식이 기능이 더 많은데, 더 큰 개념이 아닌가?
		// 자바의 규칙이 그러하다.
	}
}

class Customer {
	private int customerID;// 고객번호
	private String customerName;// 고객명
	protected String customerGrade;// 고객 등급
	int bonusPoint;// 포인트
	double bonusRatio;// 포인트 적용율.

	public Customer() {
		customerGrade = "silver";
		bonusRatio = 0.01;
	}

	public Customer(int customerID, String customerName) {
		this.customerID = customerID;
		this.customerName = customerName;
		customerGrade = "silver";
		bonusRatio = 0.01;
	}

	public int calcPrice(int price) {
		bonusPoint += price * bonusRatio;
		return price;
	}

	public String showCustomerInfo() {
		return customerName + "님의 등급은 " + customerGrade + "입니다.";
	}

}

class VIPCustomer extends Customer {
	private int agentID;
	double saleRatio;

	public VIPCustomer() {
		customerGrade = "VIP";
		bonusRatio = 0.05;
		saleRatio = 0.1;
	}

	public int calcPrice(int price) {
		bonusPoint += price * bonusRatio;
		return price - (int) (price * saleRatio);
	}

}

전화번호 4단계 (상속 활용)

Menu.java

package Phone;

import java.util.Scanner;

class Menu
{
	
	static void showMenu(PhoneBookManager pb)
	{
//		PhoneBookManager pb = new PhoneBookManager(); // 만악의 원흉
		System.out.println("메뉴를 선택하세요.");
		System.out.println("---------------");
		System.out.println("1. 데이터 입력");
		System.out.println("2. 데이터 검색");
		System.out.println("3. 데이터 삭제");
		System.out.println("4. 프로그램 종료");
		System.out.println("5. 전화번호 목록");
		System.out.println("---------------");
		
		Scanner sc = new Scanner(System.in);

		System.out.print("선택 : ");
		int input = sc.nextInt();

		switch (input) {
		case 1:
			System.out.println("데이터 입력을 시작합니다.");
			System.out.println("1.일반, 2.대학, 3.회사");
			int input2 = sc.nextInt();
			switch (input2) {
			case 1:
				sc.nextLine();
				System.out.print("이름 : ");
				String name = sc.nextLine();
				System.out.print("전화번호 : ");
				String number = sc.nextLine();
				System.out.print("생년월일 : ");
				String birth = sc.nextLine();
				pb.readData(name, number, birth);
				break;
			case 2:
				sc.nextLine();
				System.out.print("이름 : ");
				String name2 = sc.nextLine();
				System.out.print("전화번호 : ");
				String number2 = sc.nextLine();
				System.out.print("생년월일 : ");
				String birth2 = sc.nextLine();
				System.out.print("전공 : ");
				String major = sc.nextLine();
				System.out.print("학년 : ");
				int grade = sc.nextInt();
				pb.readData2(name2, number2, birth2, major, grade);
				break;
			case 3:
				sc.nextLine();
				System.out.print("이름 : ");
				String name3 = sc.nextLine();
				System.out.print("전화번호 : ");
				String number3 = sc.nextLine();
				System.out.print("생년월일 : ");
				String birth3 = sc.nextLine();
				System.out.print("회사 : ");
				String agent = sc.nextLine();
				pb.readData3(name3, number3, birth3, agent);
				break;

			default:
				System.out.println("잘못 입력");
				break;
			}
			
			
			// 더미 데이터 만들기.
//			pb.readData("hong0", "1111", "990201");
//			pb.readData("hong1", "1111", "990202");
//			pb.readData("hong2", "1111", "990203");
//			pb.readData("hong3", "1111", "990204");
//			pb.readData("hong4", "1111", "990205");
			break;

		case 2:
			System.out.println("데이터 검색을 시작합니다.");
			pb.searchData();
			break;

		case 3:
			System.out.println("데이터 삭제 시작합니다.");
			pb.deleteData();
			break;

		case 4:
			System.out.println("프로그램을 종료합니다.");
			sc.close();
			System.exit(0);
			break;
			
		case 5:
			System.out.println("전화번호부를 출력합니다.");
			pb.watchBook();
			break;

		default:
			System.out.println("잘못선택하셨습니다.");
			break;
		}

	} 
}

PhoneBook.java

package Phone;

public class PhoneBook {
	public static void main(String[] args) {
		PhoneBookManager manager = new PhoneBookManager();//객체 1개를 공유 해야 함.

		while (true) {
			Menu.showMenu(manager);
		}
	}
}

PhoneBookManager.java

package Phone;

import java.util.Scanner;

class PhoneBookManager // 제어 클래스
{
	Scanner sc = new Scanner(System.in);
	final int MAX = 100;
	//public PhoneInfo[] phoneList = new PhoneInfo[MAX];
	PhoneInfo[] phoneList = new PhoneInfo[MAX];// 객체 배열에 값이 초기화 됨.
	int cnt=0;

	void readData(String name, String phoneNumber, String birth) {		
		phoneList[cnt] = new PhoneInfo(name, phoneNumber, birth);
		cnt++;
		System.out.println("입력이 완료되었습니다.");
		
	}
	void readData2(String name, String phoneNumber, String birth ,String major, int year) {		
		phoneList[cnt] = new PhoneUnivInfo(name, phoneNumber, birth, major, year);
		cnt++;
		System.out.println("입력이 완료되었습니다.");
		
	}
	void readData3(String name, String phoneNumber, String birth, String agent) {		
		phoneList[cnt] = new PhoneCompanyInfo(name, phoneNumber, birth, agent);
		cnt++;
		System.out.println("입력이 완료되었습니다.");
		
	}

	void searchData() {
		System.out.print("검색할 이름 : ");
		String name2 = sc.nextLine();
		boolean isTrue = false;
//		System.out.println("cnt:"+this.cnt);//0
//		System.out.println(phoneList[0].getName());
		for (int i = 0; i < cnt; i++) {
//			System.out.println(phoneList[i].getName());
			if (name2.equals(phoneList[i].getName())) {
				phoneList[i].showPhoneInfo();
				isTrue = true;
			}
		}
		System.out.println(isTrue == true ? "" : "데이터가 없습니다.\n");
	}

	void deleteData() {
		System.out.print("검색할 이름 : ");
		String name3 = sc.nextLine();
		boolean isTrue = true;
		for (int i = 0; i < cnt; i++) {
			if (name3.equals(phoneList[i].getName())) {
				for(int j = 0; j<cnt-1; j++) {
					phoneList[j] = phoneList[j+1];
				}
				cnt--;
				System.out.println("데이터 삭제 완료");
			}else {
				isTrue = false;
			}
		}
		System.out.println(isTrue == true ? "" : "데이터가 없습니다.\n");
	}

	void watchBook() {
		for (int i = 0; i < cnt; i++) {
			phoneList[i].showPhoneInfo();
		}
	}
}// end class

PhoneInfo.java

package Phone;

class PhoneInfo   //데이터 클래스
{
	protected String name;
	protected String phoneNumber;
	protected String birth;
	//생성자
	public PhoneInfo(String name, String phoneNumber, String birth) {
		// TODO Auto-generated constructor stub
		this.name = name;
		this.phoneNumber = phoneNumber;
		this.birth = birth;
	}
	public PhoneInfo() {
		
	}

	public void showPhoneInfo(){
		System.out.println("name: "+ name);
		System.out.println("phone: "+ phoneNumber);
		if(birth!=null)
			System.out.println("birth: "+ birth);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

// 대학 친구들의 전화번호 저장
class PhoneUnivInfo extends PhoneInfo{
	private String major;
	private int year;
	
	public PhoneUnivInfo(String name, String phoneNumber, String birth ,String major, int year) {
		// TODO Auto-generated constructor stub
		this.name = name;
		this.phoneNumber = phoneNumber;
		this.birth = birth;
		this.major = major;
		this.year = year;
	}
	public PhoneUnivInfo() {
		// TODO Auto-generated constructor stub
	}
	@Override
	public void showPhoneInfo(){
		System.out.println("name: "+ name);
		System.out.println("phone: "+ phoneNumber);
		if(birth!=null)
			System.out.println("birth: "+ birth);
		System.out.println("major: " + major);
		System.out.println("year: " + year);
	}
	
}

// 회사전화번호부
class PhoneCompanyInfo extends PhoneInfo{
	private String agent;
	
	public PhoneCompanyInfo(String name, String phoneNumber, String birth, String agent) {
		// TODO Auto-generated constructor stub
		this.name = name;
		this.phoneNumber = phoneNumber;
		this.birth = birth;
		this.agent = agent;
	}
	public PhoneCompanyInfo() {
		// TODO Auto-generated constructor stub
	}
	@Override
	public void showPhoneInfo(){
		System.out.println("name: "+ name);
		System.out.println("phone: "+ phoneNumber);
		if(birth!=null)
			System.out.println("birth: "+ birth);
		System.out.println("agent: " + agent);
	}
}

'Java' 카테고리의 다른 글

Java - day12 (전화번호부 HashSet 다른풀이)  (0) 2022.03.06
Java - day11(전화번호부 5단계, 4단계 다른 방식 풀이)  (0) 2022.03.02
Java - day9  (0) 2022.02.28
Java - day8(전화번호부 3단계)  (1) 2022.02.24
Java - day7  (0) 2022.02.23
Comments