게시글 만들기 #1

Yullc·2025년 3월 25일
post-thumbnail

저번에 했던 Motivation 프로그램에 이어서 이번에는 게시글을 작성해 보려고 해.
게시글도 마찬가지로 CRUD가 가능해야하고 회원가입이랑 로그인기능을 추가적으로 구현 할 계획이야.

게시글 작성, 목록, 상세보기, 삭제, 수정, 날짜등록

이건 Motivation에서 했던 내용이라 쉽게 할 수 있지?? 뭘요..? 이거를 쉽게 하라고요?

  • 게시글 작성
int lastArticleId = 0;
        List<Article> articles = new ArrayList<>();


        while (true) {
            System.out.print("명령어) ");
            String cmd = sc.nextLine().trim();

            if (cmd.length() == 0) {
                System.out.println("명령어를 입력하세요");
                continue;
            }
            if (cmd.equals("exit")) {
                break;
            }

            if (cmd.equals("article write")) {
                System.out.println("==게시글 작성==");
                int id = lastArticleId + 1;
                System.out.print("제목 : ");
                String title = sc.nextLine().trim();
                System.out.print("내용 : ");
                String body = sc.nextLine().trim();

                Article article = new Article(id, title, body);
                articles.add(article);

                System.out.println(id + "번 글이 작성되었습니다");
                lastArticleId++;
            }
  • ArrayList에 articles변수를 만들어서 이제 여기에 값을 다 넣을거야.
  • 사용자가 article write를 입력하면 번호, 제목, 내용을 article에 저장을 할거야 그리고 articles List에 add 함수로 번호, 제목, 내용을 추가하면 데이터가 추가되겠지?
  • 그리고 Article이라는 클래스를 만들어서 여기에 변수 선언을 한 뒤, getter와 setter를 이용해서 값을 가져올거야
class Article {
    private int id;
    private String title;
    private String body;
    public Article(int id, String title, String body) {
        this.id = id;
        this.title = title;
        this.body = body;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    } ... 너무 길어서 생략할게

이제 감이 좀 잡히나?
감이요?감하니까 갑자기 홍시가 너무 먹고싶다.. 숫가락으로 퍼 먹..으면 맛있겠는걸..

  • 상세보기 작성
			else if (cmd.startsWith("article detail")) {
                System.out.println("==게시글 상세보기==");
                int id = Integer.parseInt(cmd.split(" ")[2]);
                Article foundArticle = null;
                for (Article article : articles) {
                    if (article.getId() == id) {
                        foundArticle = article;
                        break;
                    }
                }
                if (foundArticle == null) {
                    System.out.println("해당 게시글은 없습니다");
                    continue;
                }
                System.out.println("번호 : " + foundArticle.getId());
                System.out.println("제목 : " + foundArticle.getTitle());
                System.out.println("내용 : " + foundArticle.getBody());
            }
  • 상세보기는 해당 게시글의 번호, 제목, 내용을 한번에 보여주는거잖아? 그럼 뭐 이것도 article을 돌면서 내가 입력한 id값을 가져오면 되겠다!
  • 그러면 입력한 값을 split으로 잘라서 id만 쏙 빼! 그리고 article을 돌자.
  • article에 있는 getId값을 가져와서 id랑 비교하면 ~ 일치하는거를 foundArticle에 저장을 하자.
  • 만약 일치하는게 없다?! 그러면 "해당 게시글은 없습니다." 출력
  • 이제 print문으로 foundArticle에 저장된 Id, Title, Body를 출력하면 끝.
  • 게시글 삭제
			else if (cmd.startsWith("article delete")) {
                System.out.println("==게시글 삭제==");

                int id = Integer.parseInt(cmd.split(" ")[2]);

                Article foundArticle = null;

                for (Article article : articles) {
                    if (article.getId() == id) {
                        foundArticle = article;
                        break;
                    }
                }

                if (foundArticle == null) {
                    System.out.println("해당 게시글은 없습니다");
                    continue;
                }
                articles.remove(foundArticle);
                System.out.println(id + "번 게시글이 삭제되었습니다");
            }
  • 여기도 foundArticle에 값을 저장해 삭제를 할건데
    또 똑같이 article을 돌면서 입력받은 id랑 비교 할거야.
  • 여기도 마찬가지로 foundArticle이 없으면 "해당 게시글은 없습니다" 출력
  • 만약에 있으면 remove함수 알지? remove함수를 이용해 foundArticle을 삭제해주면 끝.
  • 게시글 수정
			else if (cmd.startsWith("article modify")) {
               System.out.println("==게시글 수정==");
                int id = Integer.parseInt(cmd.split(" ")[2]);
                Article foundArticle = null;
                for (Article article : articles) {
                    if (article.getId() == id) {
                        foundArticle = article;
                        break;
                    }
                }
                if (foundArticle == null) {
                    System.out.println("해당 게시글은 없습니다");
                    continue;
                }
                System.out.println("기존 제목 : " + foundArticle.getTitle());
                System.out.println("기존 내용 : " + foundArticle.getBody());
                System.out.print("새 제목 : ");
                String newTitle = sc.nextLine().trim();
                System.out.print("새 내용 : ");
                String newBody = sc.nextLine().trim();

                foundArticle.setTitle(newTitle);
                foundArticle.setBody(newBody);

                System.out.println(id + "번 게시글이 수정되었습니다");
            } else {
                System.out.println("사용할 수 없는 명령어입니다");
            }
        }
  • 마찬가지로 foundArticle을 이용해 해당 게시글을 찾아주고,
  • 새로운 newTitle과 newBod를 입력 받을거야.
  • 여기도 set으로 하면 덮어쓰기가 되면서 값이 변경 되겠지? 끝.
  • 날짜등록

날짜 등록은 jdk에 Localdatetime이라고 아주 간편한 기능이 있어서 그걸 가져다가 사용할거야.

일단 날짜 등록은 따로 클래스를 만들어서 분리를 하자.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Util {
    public static String getNowStr() {
        LocalDateTime now = LocalDateTime.now();
        String formatedNow = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return formatedNow;
    }
}
  • 보면 Util 클래스에 날짜를 가져오는 함수를 만들었어.
  • formatedNow변수에 현재 날짜를 집어 넣고 return을 하면 우리가 사용하는 Main클래스에서 getNowStr(); 이렇게 실행하면 현재 날짜가 넘어갈거야.
if (cmd.equals("article write")) {
                System.out.println("==게시글 작성==");
                int id = lastArticleId + 1;
                String regDate = Util.getNowStr();
                String updateDate = Util.getNowStr();
                System.out.print("제목 : ");
                String title = sc.nextLine().trim();
                System.out.print("내용 : ");
                String body = sc.nextLine().trim();

이런식으로 작성할때 값을 넘겨주고,

for (int i = forPrintArticles.size() - 1; i >= 0; i--) {
                    Article article = forPrintArticles.get(i);
                    if (Util.getNowStr().split(" ")[0].equals(article.getRegDate().split(" ")[0])) {
                        System.out.printf("  %d   /    %s        /    %s     /    %s   \n", article.getId(), article.getRegDate().split(" ")[1], article.getTitle(), article.getBody());
                    } else {
                        System.out.printf("  %d   /    %s        /    %s     /    %s   \n", article.getId(), article.getRegDate().split(" ")[0], article.getTitle(), article.getBody());
                    }
                }
  • getNowStr()시간이랑 getRegDate() 시간이랑 같으면 공백으로 split하고 시간만! 출력할거야. 왜냐하면 보통 게시글을 보면 오늘 올린 게시글은 시간만 나오고 어제올린 게시글은 날짜만 나오니까 시간만 나오게 할거고, 만약 else로 빠지면 날짜만 나오도록 구현 해 보았어.
profile
아자아자자

0개의 댓글