본문 바로가기
  • Let's study
BackEnd/Java

[Java] 명언 게시판 만들기(6~8단계)

by 코딩고수이고파 2026. 7. 20.
 

[Java] 명언 게시판 만들기(1~5단계) - 리팩토링

[Java] 명언 게시판 만들기(1~5단계)요구사항1단계 - 종료2단계 - 등록3단계 - 등록시 생성된 명언번호 노출4단계 - 등록할때 마다 생성되는 명언번호가 증가5단계 - 목록6단계 - 1번 명언삭제7단계 -

hyemzzi.tistory.com

요구사항

1단계 - 종료
2단계 - 등록
3단계 - 등록시 생성된 명언번호 노출
4단계 - 등록할때 마다 생성되는 명언번호가 증가
5단계 - 목록
6단계 - 1번 명언삭제
7단계 - 존재하지 않는 명언삭제에 대한 예외처리
8단계 - 명언수정

이번 단계에서는 삭제, 예외 처리, 수정 기능을 구현하였다.

삭제 기능이 추가되면서 기존의 lastNo만으로는 배열을 관리하기 어려워졌기 때문에 lastIndex 변수를 새로 추가하였다.

lastIndex를 추가한 이유

기존에는 삭제 기능이 없었기 때문에

마지막으로 생성된 명언 번호(lastNo) = 배열에 저장된 명언 개수였다.

하지만 삭제 기능이 추가되면 상황이 달라진다.

등록
1번
2번
3번

2번 삭제

등록
4번
 

이 경우

명언 번호 : 1, 3, 4
배열 개수 : 3개
lastNo : 4
 

즉,

  • lastNo는 마지막으로 발급한 번호
  • 실제 저장된 개수는 3개

가 되어 서로 다른 의미를 가지게 된다.

그래서 배열에 저장된 명언 개수를 관리하기 위해 lastIndex를 추가하였다.

 
int lastNo = 0;      // 마지막으로 발급한 명언 번호
int lastIndex = 0;   // 현재 저장된 명언 개수

등록

배열의 저장 위치는 lastIndex를 사용하도록 변경하였다.

 

wiseSayings[lastIndex] = wiseSaying;

wiseSaying.id = ++lastNo;
wiseSaying.content = content;
wiseSaying.author = author;

lastIndex++;

목록

목록 출력도 저장된 개수만큼만 순회하도록 수정하였다.

 

for (int i = lastIndex - 1; i >= 0; i--) {
    WiseSaying target = wiseSayings[i];

    System.out.println("%d / %s / %s"
            .formatted(target.id, target.author, target.content));
}

6단계 - 1번 명언삭제

명령) 삭제?id=1
1번 명언이 삭제되었습니다.

 

삭제 명령은 startsWith 메서드를 사용해서 명령이 삭제로 시작하는지 판단한다.

 

cmd.startsWith("삭제")

 

먼저 substring()과 indexOf()를 이용하여 명언 번호를 추출한다.

 

int id = Integer.parseInt(
        cmd.substring(cmd.indexOf("=") + 1).trim()
);

이 때 추출한 명언 번호와 해당 명언의 배열에서의 위치는 다르기 때문에 그대로 사용하면 안 된다. 

배열을 순회하며 삭제할 명언의 위치를 찾는다.

 

int targetIdx = -1;

for (int i = 0; i < lastIndex; i++) {
    WiseSaying w1 = wiseSayings[i];

    if (w1.id == id)
        targetIdx = i;
}

배열은 삭제 기능이 따로 없으므로, 삭제할 요소의 뒤에 있는 요소들을 한 칸씩 앞으로 당겨 삭제를 구현한다.

 

for (int i = targetIdx; i < lastIndex - 1; i++) {
    wiseSayings[i] = wiseSayings[i + 1];
}

lastIndex--;

마지막으로 삭제 완료 메시지를 출력한다.

7단계 - 존재하지 않는 명언삭제에 대한 예외처리

삭제할 명언이 존재하지 않으면 예외 메시지를 출력한다.

 

if (targetIdx == -1) {
    System.out.println("%d번 명언은 존재하지 않습니다.".formatted(id));
    return;
}

8단계 - 명언수정

수정 명령 역시 삭제 기능과 초반은 거의 동일하다.

 

명언 번호를 추출하고, 수정할 객체를 찾고, 존재하지 않는 명언이면 안내 메시지를 출력한다.

수정할 명언을 찾으면 기존 내용을 먼저 출력한 뒤 새로운 값을 입력받고 객체를 수정한다.

 

WiseSaying w1 = wiseSayings[targetIdx];

System.out.println("명언(기존) : %s".formatted(w1.content));
System.out.print("명언 : ");
w1.content = sc.nextLine();

System.out.println("작가(기존) : %s".formatted(w1.author));
System.out.print("작가 : ");
w1.author = sc.nextLine();

전체 코드

import java.util.Scanner;

public class App {

    Scanner sc = new Scanner(System.in);
    WiseSaying[] wiseSayings = new WiseSaying[10];

    String cmd = "";
    int lastNo = 0;      // 마지막으로 발급한 명언 번호
    int lastIndex = 0;   // 현재 저장된 명언 개수

    public void run() {

        System.out.println("== 명언 앱 ==");

        while (!cmd.equals("종료")) {

            System.out.print("명령) ");
            cmd = sc.nextLine();

            if (cmd.equals("등록")) {
                actionWrite();
            } else if (cmd.equals("목록")) {
                actionList();
            } else if (cmd.startsWith("삭제")) {
                actionDelete(cmd);
            } else if (cmd.startsWith("수정")) {
                actionModify(cmd);
            }
        }

        sc.close();
    }

    private void actionWrite() {

        System.out.print("명언 : ");
        String content = sc.nextLine();

        System.out.print("작가 : ");
        String author = sc.nextLine();

        WiseSaying wiseSaying = write(content, author);

        System.out.println("%d번 명언이 등록되었습니다.".formatted(wiseSaying.id));
    }

    private WiseSaying write(String content, String author) {

        WiseSaying wiseSaying = new WiseSaying();
        wiseSayings[lastIndex] = wiseSaying;

        wiseSaying.id = ++lastNo;
        wiseSaying.content = content;
        wiseSaying.author = author;

        lastIndex++;

        return wiseSaying;
    }

    private void actionList() {

        System.out.println("번호 / 작가 / 명언");
        System.out.println("----------------------");

        for (int i = lastIndex - 1; i >= 0; i--) {
            WiseSaying target = wiseSayings[i];

            System.out.println("%d / %s / %s"
                    .formatted(target.id, target.author, target.content));
        }
    }

    private void actionDelete(String cmd) {

        int id = Integer.parseInt(
                cmd.substring(cmd.indexOf("=") + 1).trim()
        );

        int targetIdx = -1;

        for (int i = 0; i < lastIndex; i++) {
            WiseSaying w1 = wiseSayings[i];

            if (w1.id == id) {
                targetIdx = i;
                break;
            }
        }

        if (targetIdx == -1) {
            System.out.println("%d번 명언은 존재하지 않습니다.".formatted(id));
            return;
        }

        for (int i = targetIdx; i < lastIndex - 1; i++) {
            wiseSayings[i] = wiseSayings[i + 1];
        }

        lastIndex--;

        System.out.println("%d번 명언이 삭제되었습니다.".formatted(id));
    }

    private void actionModify(String cmd) {

        int id = Integer.parseInt(
                cmd.substring(cmd.indexOf("=") + 1).trim()
        );

        int targetIdx = -1;

        for (int i = 0; i < lastIndex; i++) {
            WiseSaying w1 = wiseSayings[i];

            if (w1.id == id) {
                targetIdx = i;
                break;
            }
        }

        if (targetIdx == -1) {
            System.out.println("%d번 명언은 존재하지 않습니다.".formatted(id));
            return;
        }

        WiseSaying w1 = wiseSayings[targetIdx];

        System.out.println("명언(기존) : %s".formatted(w1.content));
        System.out.print("명언 : ");
        w1.content = sc.nextLine();

        System.out.println("작가(기존) : %s".formatted(w1.author));
        System.out.print("작가 : ");
        w1.author = sc.nextLine();
    }
}

 

댓글