Java

Java로 간단한 콘솔 연락처 프로그래밍

범데이 2021. 7. 9. 01:05

1.개요 

 

친한 형님께서 학원에서 숙제를 받으셔서

작은 도움을 요청하셨다.

 

도움을 드리는 김에 이 주제로 한번 포스팅을 해보고자 한다!

 

 

목표: 자바로 개발하여 콘솔에서 다룰수있는 간단한 연락처 (입력, 조회, 검색, 삭제) 기능 개발

 

 

<결과 미리보기>

처음에 실행했을때의 모습

 

전체 데이터조회(2) 기능을 수행했을때 아무 데이터도 조회되지 않는다.

 

데이터 입력(1) 기능으로 두 연락처의 이름, 전화번호, 생년월일 입력.

 

데이터 조회(2)를 했을때 입력한 연락처 리스트가 조회된다.
데이터 검색(3) 기능을 통해 이름으로 연락처를 검색한다.
데이터 삭제(4) 기능을 이용해 저장된 연락처를 삭제한다.
연락처 리스트를 조회하여 연락처가 삭제되었음을 확인할 수 있다.
마지막으로 프로그램 종료(5).

 

2. 구현코드

2.1 Student Class

Class의 이름은 Student이고, 멤버변수(속성) 으로 String type의 name, phone, birth가 있다.

각각의 getter, setter 메서드가 있고, showInfo()메서드를 호출하면 해당 멤버변수의 값들을 print로 출력한다.

class Student{
	//멤버변수
	private String name, phone, birth;
	//생성자
	Student(String name, String phone, String birth){
		this.name = name;
		this.phone = phone;
		this.birth = birth;
	}
	
	//getter setter
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}
	public void setPhone(String tel) {
		this.phone = tel;
	}
	
	public String getBirth() {
		return birth;
	}
	public void setBirth(String birth) {
		this.birth = birth;
	}
	
	public void showInfo() {
		System.out.println("name: " + name);
		
		//phone이 빈 값이면 
		if(!phone.isEmpty()) {
			System.out.println("phone: " + phone);
		}
		if(!birth.isEmpty()) {
			System.out.println("birth: " + birth + "\n");
		}
	}
}

 

2.2 main함수

Student 객체를 저장할 리스트와, 인덱스(현재 입력된 학생 순서) 변수가 정의되어있고,

 

사용자의 입력을 받을수 있는 Scanner 객체 정의과,

프로그램이 끝날때까지 계속 입력을 받을수 있게 while(true) 블럭으로 감싸진 내용이 있다.

각각의 입력 번호에 맞게 메서드를 실행한다.

1: inputData() - 입력

2. showData() - 조회

3. searchInfo() - 검색

4. deleteData() - 삭제

5. return (종료)

	// 100개 배열 생성
	static Student[] stList = new Student[100];
	static int idx = 0;
    
	// main
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		while(true) {
			System.out.println("선택하세요.....");
			System.out.println("1. 데이터 입력");
			System.out.println("2. 전체데이터 조회");
			System.out.println("3. 데이터 검색");
			System.out.println("4. 데이터 삭제");
			System.out.println("5. 프로그램 종료");
			
			int selectNum = sc.nextInt();
			switch(selectNum) {
			case 1:
				inputData();
				break;
			case 2:
				showData();
				break;
			case 3:
				searchInfo();
				break;
			case 4:
				deleteData();
				break;
			case 5:
				System.out.println("프로그램을 종료합니다.");
				return;
			}
		}
	}

 

2.2.1 inputData메서드

Scanner 객체의 next()메서드를 이용해 name, phone, birth String값을 입력받고,

이를 stList(Student객체를 저장할 리스트변수)에 저장한다.

 

	//1. 데이터 입력
	private static void inputData() {
		Scanner sc = new Scanner(System.in);
		System.out.print("데이터 입력을 시작합니다..\n이름: ");
		String name = sc.next();
		System.out.print("전화번호: ");
		String phone = sc.next();
		System.out.print("생년월일: ");
		String birth = sc.next();
		System.out.println("데이터 입력이 완료되었습니다.\n");
		
		stList[idx++] = new Student(name, phone, birth);
	}


2.2.2 showData메서드

현재까지 stList(Student객체를 저장하는 리스트 변수)에 저장된 Student객체들의 정보를 print로 화면에 출력한다.

for문은 0번 인덱스부터, 현재 입력된 인덱스(idx)까지 반복한다.

	//2. 전체 데이터 출력
	private static void showData() {
		System.out.println("\n----------전체 리스트 조회----------");
		for(int i=0; i<idx; i++) {
			stList[i].showInfo();
		}
		System.out.println("------------------------------");
	}

 

2.2.3 searchInfo메서드

데이터 검색을 수행하는 메서드이다.

Scanner로 사용자에게 이름을 입력받은 후,

현재 저장된 Student객체들(stList)의 리스트 방들을 조회한다.

만일 리스트 내 저장된 객체중에 이름이 일치하는 객체가 있다면, Student객체의 showInfo메서드를 통해

해당 Student객체의 내용을 출력한다.

	//3. 검색
	private static void searchInfo() {	
		Scanner sc = new Scanner(System.in);
		System.out.print("데이터 검색을 시작합니다..\n이름 : ");
		String inputName = sc.nextLine();
		
		for(int i=0; i<idx; i++) {
			// 입력한 이름이 stList에 일치하는게 존재한다면,
			if(stList[i].getName().equals(inputName)) {
				//해당 정보 출력
				stList[i].showInfo();
			}
		}
		System.out.println("데이터 검색이 완료되었습니다.");
	}

 

2.2.4 deleteData메서드

데이터 삭제를 수행하는 메서드이다.

Scanner로 삭제할 이름을 사용자로부터 입력 받은 후,

Student객체들을 담고있는 stList에서 이름이 일치하는 객체가 있다면,

해당 객체의 index를 findIdx에 대입해준다.

 

findIdx가 -1이 아니라면(일치하는 객체가 있다면) 

해당 객체의 정보를 지우고, 데이터를 앞당겨준다.

(만일 1부터 5까지의 데이터가 있는데 3이 삭제된다고 가정하면,

4→3, 5→4 와 같이 데이터를 앞당겨주고, 데이터 개수를 표시해주는 idx변수의 값을 1 빼준다.)

	//4. 데이터 삭제
	private static void deleteData() {
		Scanner sc = new Scanner(System.in);
		System.out.print("데이터 삭제를 시작합니다..\n이름 : ");
		String inputName = sc.nextLine();
		int findIdx = -1; // 배열중 찾은 인덱스를 저장
		
		for(int i=0; i<idx; i++) {
			if(stList[i].getName().equals(inputName)) {
				findIdx = i;
			}
		}
		
		// 삭제할 데이터가 존재한다면
		if (findIdx != -1) {
			// 찾은 인덱스가 마지막 인덱스가 아니라면,
			// 데이터를 다음인덱스 데이터로 덮어버림(마지막인덱스까지)
			for(int i=findIdx; i < idx-1; i++){
				stList[i].setName(stList[i+1].getName());
				stList[i].setPhone(stList[i+1].getPhone());
				stList[i].setBirth(stList[i+1].getBirth());
			}
			idx--; // 데이터 개수 1 감소
		}
		System.out.println("데이터 삭제가 완료되었습니다.");
	}

 

 

2.3 전체코드

이렇게해서 전체 코드는 다음과 같다:

package com.bumday.contactsample;

import java.util.Scanner;

class Student{
	//멤버변수
	private String name, phone, birth;
	//생성자
	Student(String name, String phone, String birth){
		this.name = name;
		this.phone = phone;
		this.birth = birth;
	}
	
	//getter setter
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public String getPhone() {
		return phone;
	}
	public void setPhone(String tel) {
		this.phone = tel;
	}
	
	public String getBirth() {
		return birth;
	}
	public void setBirth(String birth) {
		this.birth = birth;
	}
	
	public void showInfo() {
		System.out.println("name: " + name);
		
		//phone이 빈 값이면 
		if(!phone.isEmpty()) {
			System.out.println("phone: " + phone);
		}
		if(!birth.isEmpty()) {
			System.out.println("birth: " + birth + "\n");
		}
	}
}

public class ContactSample {
	// 100개 배열 생성
	static Student[] stList = new Student[100];
	static int idx = 0;

	// main
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		while(true) {
			System.out.println("선택하세요.....");
			System.out.println("1. 데이터 입력");
			System.out.println("2. 전체데이터 조회");
			System.out.println("3. 데이터 검색");
			System.out.println("4. 데이터 삭제");
			System.out.println("5. 프로그램 종료");
			
			int selectNum = sc.nextInt();
			switch(selectNum) {
			case 1:
				inputData();
				break;
			case 2:
				showData();
				break;
			case 3:
				searchInfo();
				break;
			case 4:
				deleteData();
				break;
			case 5:
				System.out.println("프로그램을 종료합니다.");
				return;
			}
		}
	}

	//1. 데이터 입력
	private static void inputData() {
		Scanner sc = new Scanner(System.in);
		System.out.print("데이터 입력을 시작합니다..\n이름: ");
		String name = sc.next();
		System.out.print("전화번호: ");
		String phone = sc.next();
		System.out.print("생년월일: ");
		String birth = sc.next();
		System.out.println("데이터 입력이 완료되었습니다.\n");
		
		stList[idx++] = new Student(name, phone, birth);
	}
	
	//2. 전체 데이터 출력
	private static void showData() {
		System.out.println("\n----------전체 리스트 조회----------");
		for(int i=0; i<idx; i++) {
			stList[i].showInfo();
		}
		System.out.println("------------------------------");
	}

	
	//3. 검색
	private static void searchInfo() {	
		Scanner sc = new Scanner(System.in);
		System.out.print("데이터 검색을 시작합니다..\n이름 : ");
		String inputName = sc.nextLine();
		
		for(int i=0; i<idx; i++) {
			// 입력한 이름이 stList에 일치하는게 존재한다면,
			if(stList[i].getName().equals(inputName)) {
				//해당 정보 출력
				stList[i].showInfo();
			}
		}
		System.out.println("데이터 검색이 완료되었습니다.");
	}
	
	//4. 데이터 삭제
	private static void deleteData() {
		Scanner sc = new Scanner(System.in);
		System.out.print("데이터 삭제를 시작합니다..\n이름 : ");
		String inputName = sc.nextLine();
		int findIdx = -1; // 배열중 찾은 인덱스를 저장
		
		for(int i=0; i<idx; i++) {
			if(stList[i].getName().equals(inputName)) {
				findIdx = i;
			}
		}
		
		// 삭제할 데이터가 존재한다면
		if (findIdx != -1) {
			// 찾은 인덱스가 마지막 인덱스가 아니라면,
			// 데이터를 다음인덱스 데이터로 덮어버림(마지막인덱스까지)
			for(int i=findIdx; i < idx-1; i++){
				stList[i].setName(stList[i+1].getName());
				stList[i].setPhone(stList[i+1].getPhone());
				stList[i].setBirth(stList[i+1].getBirth());
			}
			idx--; // 데이터 개수 1 감소
		}
		System.out.println("데이터 삭제가 완료되었습니다.");
	}
}

 

 

3. 끝내며

간단한 프로그래밍 같지만, 생각을 기르는데 훈련이 되는듯 하다!

더 좋은 방법이 있을것 같은데, 포스팅 해두고 다음에 다시 내용을 보강하기로.

 

 

궁금하신점이나 모든 문의사항은 댓글로 남겨주세요

 

감사합니다.

반응형

'Java' 카테고리의 다른 글

[Java] Null Check  (0) 2022.11.25
[Java] JSON 변환 라이브러리 Jackson에 대해  (0) 2022.11.22
[Java] 예외처리  (0) 2022.09.22
[Java] 빌더 패턴(Builder Pattern)에 대해  (0) 2022.08.30
[Java] Ubuntu에 AdoptOpenJDK 설치  (0) 2022.08.10