야나도 프로젝트

나도 개발자 될수있어

JAVA

JAVA 주소록 관리 프로그램

jmeen 2021. 8. 2. 20:22
728x90

JAVA 미니 프로젝트 : 주소록 관리 프로그램

* 조건

  • 데이터는 텍스트로 관리한다. 
  • 데이터 구분은 , 로 한다.
  • 저장 클래스 필드는 이름 , 핸드폰번호, 전화번호

데이터 텍스트 파일 예시

출력 예시

1. 저장 클래스 생성

요구한 대로 이름과, 핸드폰번호, 집전화번호를 필드로 생성했다.

출력을 위해 toString()은 오버라이드하여 출력 포맷으로 맞춰주었다.

package com.java.miniproject;

public class PersonInfo {
	private int num;
	private String name;
	private String hp;
	private String tel;

	public PersonInfo(String name, String hp, String tel) {
		this.name = name;
		this.hp = hp;
		this.tel = tel;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public String getName() {
		return name;
	}

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

	public String getCellphone() {
		return hp;
	}

	public void setCellphone(String hp) {
		this.hp = hp;
	}

	public String getHomephone() {
		return tel;
	}

	public void setHomephone(String tel) {
		this.tel = tel;
	}

	public void showInfo() {
		System.out.printf("%d. %s\t%s\t%s%n", num, name, hp, tel);
	}

	@Override
	public String toString() {
		String result = String.format("%d. %s\t%s\t%s", num, name, hp, tel);
		return result;
	}
}

 

2. 메인코드

코드를 배운지 얼마 안되었기 때문에, 고급 기술은 쓸줄 모른다.

기능을 하나씩 만들고, 필요할때 불러오는 방식으로 코드를 작성했다.

 

List Array 기능을 쓰면, 삭제된 줄이 그 밑줄로 채워지기 때문에, 원하는 대로 차례대로 만들수 있다.

 

하지만 순서대로 번호를 매겨야하기때문에, update 기능으로 마지막에 한번씩 업데이트하여 번호를 다시 매겨줬다.

지금은 데이터가 짧기때문에 유효하지만, 추후 큰 데이터를 사용해야하면 어려울 것 같다.

 

물론 새로운 데이터가 추가되면, 바로 DB txt파일에 업데이트 하고, 삭제하여도 바로 업데이트 하였다.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class contactmanager {
	static final String rootPath = System.getProperty("user.dir") + "\\files\\";
	static final String address = rootPath + "PhoneDB.txt";

	public static void main(String[] args) {
		List<PersonInfo> person = new ArrayList<>();
		readTxt(person); // txt파일 읽기
		run(person);
	}

	private static void run(List<PersonInfo> person) {
		boolean runx = true;
		int num = 0;
		String serchstr = "";
		System.out.println("***************************************");
		System.out.println("*          전화번호 관리 프로그램           *");
		System.out.println("***************************************");
		while (runx) {
			Scanner sc = new Scanner(System.in);
			System.out.println("1.리스트   2.등록   3.삭제   4.검색   5.종료");
			System.out.println("---------------------------------------");
			System.out.print("메뉴번호 >> ");
			num = sc.nextInt();

			switch (num) {
			case 1:
				System.out.println();
				System.out.println("<1. 리스트>");
				showinfo(person);
				System.out.println();
				break;
			case 2:
				System.out.println();
				System.out.println("<2. 등록>");
				add(sc, person);
				break;
			case 3:
				System.out.println();
				System.out.println("<3. 삭제>");
				System.out.print("번호 >> ");
				delete(sc, person);
				break;
			case 4:
				System.out.println();
				System.out.println("<4. 검색>");
				System.out.print("이름 >> ");
				serchstr = sc.next();
				search(person, serchstr);
				System.out.println();
				break;
			case 5:
				System.out.println();
				System.out.println("***************************************");
				System.out.println("*              감사합니다                *");
				System.out.println("***************************************");
				sc.close();
				runx = false;
				break;
			default:
				System.out.println("[다시 입력해 주세요]");
				System.out.println();

			}
		}
	}

	// 이름에서 단어를 포함하는 리스트 검색
	private static void search(List<PersonInfo> person, String str) {
		for (int i = 0; i < person.size(); i++) {
			PersonInfo serchperson = (PersonInfo) person.get(i);
			if (serchperson.getName().contains(str)) {
				System.out.println(serchperson.toString());
			}
		}
	}

	// 선택한 번호 삭제
	private static void delete(Scanner sc, List<PersonInfo> person) {
		int del = sc.nextInt();
		person.remove(del - 1);
		update(person);
		System.out.println();
		wirteTxt(person);
		System.out.println("[삭제되었습니다.]");
	}

	// 리스트 출력
	private static void showinfo(List<PersonInfo> person) {
		for (int i = 0; i < person.size(); i++) {
			System.out.println(person.get(i).toString());
		}
	}

	// 리스트에 추가
	private static void add(Scanner sc, List<PersonInfo> person) {
		String name;
		String hp;
		String tel;
		System.out.print(">이름    : ");
		name = sc.next();
		System.out.print(">휴대전화 : ");
		hp = sc.next();
		System.out.print(">집전화   : ");
		tel = sc.next();
		person.add(new PersonInfo(name, hp, tel));
		update(person);
		System.out.println();
		wirteTxt(person);
		System.out.println("[등록되었습니다.]");
	}

	// 번호 순차대로 다시 넘버링
	private static void update(List<PersonInfo> person) {
		for (int i = 0; i < person.size(); i++) {
			PersonInfo n = (PersonInfo) person.get(i);
			n.setNum(i + 1);
		}
	}

	// 텍스트 읽어오기
	private static List<PersonInfo> readTxt(List<PersonInfo> person) {
		Reader fr = null;
		BufferedReader br = null;
		try {
			fr = new FileReader(address);
			br = new BufferedReader(fr);
			String line = "";
			String[] words = new String[3];
			while ((line = br.readLine()) != null) {
				words = line.split(",");
				person.add(new PersonInfo(words[0], words[1], words[2]));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		update(person);
		return person;
	}

	private static void wirteTxt(List<PersonInfo> person) {
		Writer fw = null;
		BufferedWriter bw = null;

		try {
			// 주스트림
			fw = new FileWriter(address);

			// 메인스트림
			bw = new BufferedWriter(fw);

			for (int i = 0; i < person.size(); i++) {
				PersonInfo writeperson = (PersonInfo) person.get(i);
				bw.write(writeperson.getName() + ",");
				bw.write(writeperson.getCellphone() + ",");
				bw.write(writeperson.getHomephone());
				bw.write("\r\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				bw.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

 

3. 결과

 

이렇게 미니 프로젝트 / 주소록 만들기를 완성해봤다.

'JAVA' 카테고리의 다른 글

JAVA 기반 Github 세팅 / 업로드  (0) 2021.08.11
JAVA 변수/자료형/식별자  (0) 2021.08.11
JAVA 기초 / IDE(eclipse) 설치  (0) 2021.08.11
프로그램기초  (0) 2021.08.11
JAVA 주소록 관리 프로그램 개선  (0) 2021.08.10