danDevlog

Java - day11(전화번호부 5단계, 4단계 다른 방식 풀이) 본문

Java

Java - day11(전화번호부 5단계, 4단계 다른 방식 풀이)

단데기이 2022. 3. 2. 23:35
728x90

4단계와의 차이점 : 객체 배열 이용대신, HashSet과 Iterator을 이용하여 구현 (PhoneBookManager.java파일만 변경)

package Phone;

import java.util.HashSet;
import java.util.Iterator;
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];// 객체 배열에 값이 초기화 됨.
	HashSet<PhoneInfo> phoneList = new HashSet<>();
	int cnt=0;

	void readData(String name, String phoneNumber, String birth) {		
//		phoneList[cnt] = new PhoneInfo(name, phoneNumber, birth);
		cnt++;
		phoneList.add(new PhoneInfo(name, phoneNumber, birth));
		System.out.println("입력이 완료되었습니다.");
	}
	void readData2(String name, String phoneNumber, String birth ,String major, int year) {		
//		phoneList[cnt] = new PhoneUnivInfo(name, phoneNumber, birth, major, year);
		phoneList.add(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);
		phoneList.add(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;
//			}
//		}
		Iterator<PhoneInfo> it = phoneList.iterator();
		while(it.hasNext()) {
			PhoneInfo p = it.next();
			if (name2.equals(p.getName())) {
				p.showPhoneInfo();
				isTrue = true;
			}
		}
		System.out.println(isTrue == true ? "" : "데이터가 없습니다.\n");
	}

	void deleteData() {
		System.out.print("검색할 이름 : ");
		String name3 = sc.nextLine();
		boolean isTrue = false;
//		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;
//			}
//		}
		
		Iterator<PhoneInfo> it = phoneList.iterator();
		while(it.hasNext()) {
			PhoneInfo p = it.next();
			if (name3.equals(p.getName())) {
				it.remove();
				isTrue = true;
				System.out.println("데이터 삭제 완료");
			}
		}
		System.out.println(isTrue == true ? "" : "데이터가 없습니다.\n");
	}

	void watchBook() {
//		for (int i = 0; i < cnt; i++) {
//			phoneList[i].showPhoneInfo();
//		}
		Iterator<PhoneInfo> it = phoneList.iterator();
		while(it.hasNext()) {
			PhoneInfo p = it.next();
			p.showPhoneInfo();
		}
	}
}// end class

 

// 전화번호 4단계 해설.
class Menu
{
	static void showMenu(){
		// 객체 생성 없이 호출할 수 있다.
		// 클래스명.showMenu();
		//1. 2.... 3..
		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("---------------");
		// 안내 메세지의 역할.
		// 클래스 분리와 static 의 사용을 연습.
	} 
}

import java.util.Scanner;
// 학교 연락처, 회사 연락처 등록해 보기.
class PhoneBook {
	static Scanner sc = new Scanner(System.in);
	public static void main(String[] args) {
		PhoneBookManager manager = new PhoneBookManager();
		// 메소드 안에 선언한 변수는 메소드가 끝나면 사라짐. 사용 불가.
		// 공유 변수는 메소드 바깥쪽, 클래스 안쪽에 선언. 여러 메소드에서 해당
		변수를 공유.
		while (true) {
			Menu.showMenu();// Menu 클래스의 showMenu 메소드 호출.
			// 객체 생성후 접근이 아니다.
			// 메뉴를 반복 표시하면서, 선택에 따라 처리를 분기.
			int input = sc.nextInt();
			if (input == 1) {// 입력.
				manager.readData();
			} else if (input == 2) {// 검색
				manager.searchData();
			} else if (input == 3) {// 삭제
				manager.deleteData();
			} else if (input == 4) {// 삭제
				manager.allData();
			} else {
				break;// 프로그램 종료.
			}
		}
		sc.close();// 사용한 입력 처리관련 자원을 운영체제에 반납.
	}
} // class end


class PhoneBookManager // 제어 클래스
{
	final int MAX = 100;
	PhoneInfo[] phoneList = new PhoneInfo[MAX];
	int cnt = 0;
	void readData() {// 입력처리 메소드
		// 입력 선택후, 다시 메뉴 보이기. 1. 일반, 2.대학, 3.회사.
		PhoneBook.sc.nextLine();
		System.out.println("데이터 입력을 시작합니다");
		System.out.println("1.일반, 2.대학, 3.회사");
		int choice = PhoneBook.sc.nextInt();// 사용자 선택.
		PhoneBook.sc.nextLine();// 엔터 소거용.
		System.out.print("이름:");
		String name = PhoneBook.sc.nextLine();
		System.out.print("전화번호:");
		String phoneNumber = PhoneBook.sc.nextLine();
		switch (choice) {
		case 1:
			// PhoneInfo pi = new PhoneInfo(name, phoneNumber);
			// phoneList[cnt++]=pi;
			phoneList[cnt++] = new PhoneInfo(name, phoneNumber);
			break;
		case 2:
			System.out.print("전공:");
			String major = PhoneBook.sc.nextLine();
			System.out.print("학년:");
			int year = PhoneBook.sc.nextInt();
			phoneList[cnt++] = new PhoneUnivInfo(name, phoneNumber, 
					major, year);
			break;
		case 3:
			System.out.print("회사:");
			String company = PhoneBook.sc.nextLine();
			phoneList[cnt++] = new PhoneCompanyInfo(name, phoneNumber, 
					company);
			break;
		}
		// 전달값 3개를 처리하는 생성자가 없으므로 에러,
		// 해당 에러 위에 커서를 두면,
		// 선택1) 지워라.
		// 선택2) 해당 생성자를 만들어라.
		// phoneList[0] = new PhoneInfo("1", "", "");
		// phoneList[1] = new PhoneInfo("2", "", "");
		// phoneList[2] = new PhoneInfo("3", "", "");
		// phoneList[3] = new PhoneInfo("4", "", "");
		// phoneList[4] = new PhoneInfo("5", "", "");
		// cnt = 5;
		System.out.println("데이터 입력이 완료되었습니다.\n");
		// \n은 줄바꿈
	}
	void searchData() {// 검색 처리 메소드
		// 똑같은 이름의 연락처는 없다가 전제.
		// 이름을 입력 받으면, 이름을 등록된 연락처에서 검색후,
		// 있다면, 연락처 표시.
		// 없다면, 찾는 연락처 없음 표시.
		System.out.println("데이터 검색을 시작합니다.");
		PhoneBook.sc.nextLine();// 엔터값 제거
		System.out.print("이름:");
		String name = PhoneBook.sc.nextLine();
		int i = searchIndex(name);
		System.out.println(i + "번째 값을 찾았습니다.");
		if (i != 200) {
			phoneList[i].showPhoneInfo();
		} else {
			System.out.println("찾는 값이 존재하지 않습니다.\n");
		}
	}
	int searchIndex(String name) {
		int index = 200; // 객체 배열의 인덱스가 0~99
		// 검색 실패시 index의 기본값을 리턴하므로, 범위에 없는 값 설정.
		for (int i = 0; i < cnt; i++) {
			// cnt를 사용하는 이유 : 연락처 등록은 1~100건 가능.
			// 몇건을 입력했는지 모르므로 입력된 갯수 사용.
			// phoneList.length 는 항상 100.
			if (name.equals(phoneList[i].getName())) {
				// name 으로 연락처 객체에 접근하지 않는 이유는,
				// 사용자 요청이 해당 값을 private 으로 요구했기 때문에.
				// 직접 접근해서 사용할 수 없고,
				// public 한 메소드를 통해서 값을 읽어 올 수 있음. -
				자바의 캡슐화.
				// getter : private 한 값 읽어 오기.
				// setter : private 한 값 저장 하기.
				index = i;
			}
		}
		return index;
	}
	void deleteData() {// 삭제 처리 메소드
		// 일치하는 값 찾기.
		// 찾는 값 삭제.
		// 0,1,2,3,4 상황에서 3번 삭제.
		// 0,1,2,null,4 컴파일러는 순차적 접근하면서 널포인트 에러 발생 시킴.
		// 0,1,2,4 뒤쪽에 값을 삭제한 자리로 당겨오기.
		// 위처럼 변경해야 삭제 이후에도 검색 가능.
		System.out.println("데이터 삭제를 시작합니다...");
		PhoneBook.sc.nextLine();
		System.out.print("이름:");
		String name = PhoneBook.sc.nextLine();
		int i = searchIndex(name);
		if (i != 200) {
			arrSort(i);
			System.out.println(i + "번째 데이터가 삭제 되었습니다.");
			cnt--;
		} else {
			System.out.println("찾는 값이 없습니다.");
		}
		System.out.println("현재 등록된 연락처:" + cnt + "\n");
	}
	void arrSort(int index) {
		for (int i = index; i < cnt; i++) {
			phoneList[i] = phoneList[i + 1];
			// 삭제할 값은 index
			// 뒤쪽의 배열 값들을 1개씩 당겨서 찾은 배열을 덮어쓰기.
			// 입력된 갯수 만큼만.
			// 1,2,3,4,5
			// 1,2,3,null,5
			// 1,2,3,5,5
			// phoneList[4]=phoneList[4+1];
			// 1,2,3,5,null, null....
			// 1,2,3,5,6,null
		}
		// System.out.println(phoneList.length);//100
		phoneList[cnt] = null;
		// 필요 없음. 갯수 만큼으로 검색하니, 갯수에서 벗어난 null 아닌 값은 체크
		안함.
		// 그래도, 혹시 몰라서 널 처리.
		// System.out.println(phoneList.length);//100
		// 1,2,3,5,5
		// 1,2,3,5,null
		// 4개면, 0~3
		// phoneList[3]=phoneList[4];
		// phoneList[3]=null;
	}
	public void allData() {
		// TODO Auto-generated method stub
		for (int i = 0; i < cnt; i++) {
			phoneList[i].showPhoneInfo();
		}
	}
}// end class


class PhoneInfo // 데이터 클래스
{
	private String name;
	private String phoneNumber;
	// private String birth;
	public PhoneInfo(String name2, String phoneNumber2) {
		// TODO Auto-generated constructor stub
		this.name = name2;
		this.phoneNumber = phoneNumber2;
		// this.birth = birthday;
	}
	// 생성자 역할 : 객체를 초기화. 클래스를 통해서 동일한 형식의 객체 생성.
	// int a=5; 정수형 변수a를 5로 초기화.
	// 객체와 클래스의 차이 : 붕어빵과 붕어빵틀.
	// 생성자 특징 : 리턴 타입이 없다.
	// (매개변수가 없는) 기본 생성자 명시하지 않는다면 컴파일러가자동생성.
	// 생성자의 이름은 클래스명과 같다.
	public void showPhoneInfo() {
		System.out.println("name: " + name);
		System.out.println("phone: " + phoneNumber);
		// if (birth != null)
		// System.out.println("birth: " + birth);
	}
	public String getName() {
		// TODO Auto-generated method stub
		return this.name;
	}
} // PhoneInfo end
public class PhoneUnivInfo extends PhoneInfo {
	// *전공: String major
	// *학년: int year
	String major;
	int year;
	public PhoneUnivInfo(String name2, String phoneNumber2, String major, int
			year) {
		super(name2, phoneNumber2);
		this.major = major;
		this.year = year;
	}
	@Override
	public void showPhoneInfo() {
		// TODO Auto-generated method stub
		super.showPhoneInfo();
		System.out.println("major: " + major);
		System.out.println("year: " + year);
	}
}
public class PhoneCompanyInfo extends PhoneInfo {
	String company;
	public PhoneCompanyInfo(String name2, String phoneNumber2, String comp) {
		super(name2, phoneNumber2);
		// 부모 객체의 필드값 초기화,
		company = comp;// 자식 객체의 필드값 초기화.
	}
	@Override
	public void showPhoneInfo() {
		// TODO Auto-generated method stub
		super.showPhoneInfo();
		System.out.println("company: " + company);
	}
}

'Java' 카테고리의 다른 글

Java - day13 (자바 연습문제)  (0) 2022.03.07
Java - day12 (전화번호부 HashSet 다른풀이)  (0) 2022.03.06
Java - day10(배열, 상속, 전화번호 4단계)  (0) 2022.02.28
Java - day9  (0) 2022.02.28
Java - day8(전화번호부 3단계)  (1) 2022.02.24
Comments