게시글 작성은 설계도를 보고 진짜 실체를 만들어내는 과정이라고 해석한다.
Article article = new Article(id, title, body);
articles.add(article);
new Article(...) : Article이라는 설계도를 보고, 방금 위에서 입력받은 id, title, content 재료를 다 집어넣어서 새로운 진짜 게시글 1개를 만들어라 라는 뜻이다.Article article = : 그렇게 만들어진 진짜 게시글(우변)에 article이라는 이름표를 붙여서 내가 컨트롤하겠다는 뜻이다. (앞의 대문자 Article은 타입(설계도 종류)이고, 소문자 article은 제가 마음대로 지은 이름표이다.)articles : 맨 위에서 만든 게시글을 담아주는 리스트(상자)이다..add() : 리스트가 제공하는 기능으로, 상자 안에 무언가를 집어넣으라는 뜻이다.article : 위 Article article = new Article(id, title, content); 여기서 이름표 붙인 진짜 게시글이다.작성된 게시글을 꺼내어 볼 때는 최신 글부터 역순으로 보여주기 위한 장치가 필요하다.
for (int i = articles.size() -1; i >= 0; i--) {
Article article = articles.get(i);
System.out.printf("%d / %s / %s \n", article.getId(), article.getTitle(), article.getContent());
}
// 리스트를 0부터 센다.
//int i = articles.size() - 1은 총 개수에서 제일 끝자리부터 시작한다는 뜻이다.
//-1은 저장공간이 3개이면 0부터 시작하여 2까지의 3칸이 마련되기에 최신것을 부르려면 -1을 해야 한다.
// 줄여가며 하나씩 간다.
// 리스트에 있는 게시글을 뒤에서 부터 (최신순으로) 꺼낸다.
// 상자 리스트에서 i번째 게시글을 꺼내서
article이라는 이름표를 붙여주는 과정이 출력문 바로 위에서 필요하다.
//get(i)는 그 상자에서 i번째 칸에 있는 게시물 하나를 손으로 끄집어내는 것이다.
// 꺼낸 게시물에article이라는 임시 이름표를 붙여준다.
// 이렇게 해야 바로 밑줄에서article.getTitle()처럼 그 게시물에게 말을 걸 수 있기 때문이다.
// 어떤article인지 컴퓨터가 몰라서 위의 코드를 입력해줘야 한다.
게시글 삭제 기능은 먼저 삭제할 대상의 번호를 찾고, 리스트에서 해당 객체를 지우는 방식으로 작동한다.
else if (cmd.startsWith("article delete")) {
System.out.println("게시글 삭제");
int id = Integer.parseInt(cmd.split(" ")[2]); //-1
Article foundArticle = null;
for (Article article : articles) {
if (article.getId() == id) {
foundArticle = article; //-1
break;
}
}
if (foundArticle == null) {
System.out.println("해당 게시물은 없습니다.");
} else {
articles.remove(foundArticle);
System.out.printf("%s 번 게시글이 삭제되었습니다.", id);
}
}
밑은 위 로직을 개선하고 상세하게 풀이한 설명이다.
Article foundArticle = null;
// 결론은 찾은 위치(게시물)를 저장할 건데, 아직은 못 찾았으니까 비어있다(null)고 해두자 라는 뜻입니다.
for (Article article : articles) {
// 보관함(List)에 있는 게시물들을 처음부터 끝까지 하나씩 꺼내서 확인해보는 과정
if (article.getId() == id) {
// article.getId(): 방금 사물함에서 막 꺼내서 내 손에 쥔 그 게시물의 실제 번호이다.
// id: 사용자가 맨 처음에 입력했던 내가 찾고 있는 바로 그 번호이다.
foundArticle = article;
// 찾았다는 표시를 남겨야 합니다
break;
}
}
if (foundArticle == null) {
System.out.printf("%d번 게시글은 존재하지 않습니다.\n", id);
} else {
articles.remove(foundArticle);
// 제거하는 함수는 remove();이다.
System.out.printf("%d번 게시글이 삭제되었습니다.\n", id);
}
else if (cmd.startsWith("article detail ")) {
System.out.println("== 게시글 상세보기 ==");
// 1. "article detail 1" 이라는 문장을 띄어쓰기 기준으로 쪼개서, 3번째 조각("1")을 진짜 숫자로 바꿉니다.
String[] cmdBits = cmd.split(" ");
//잘린 조각들이 cmdBits라는 칸막이 상자(배열)에 순서대로 담긴다.
//[0]번 칸 : "article"
//[1]번 칸 : "delete"
//[2]번 칸 : "5" (우리가 필요한 글 번호)
int id = Integer.parseInt(cmdBits[2]);
//[2]번 칸 : "5" (우리가 필요한 글 번호)를 숫자로 변환.
Article foundArticle = null; // 찾은 게시글을 담을 '임시 빈 상자'
// 2. 리스트 상자를 처음부터 끝까지 샅샅이 뒤집니다.
for (Article article : articles) {
if (article.getId() == id) { // "너 번호가 내가 찾는 번호랑 똑같아?"
foundArticle = article; // 찾았다면 임시 상자에 담고
break; // 그만 찾고 나옵니다.
}
}
// 3. 다 뒤졌는데도 임시 상자가 비었다면 = 없는 번호
if (foundArticle == null) {
System.out.printf("%d번 게시글은 없습니다\n", id);
} else {
// 상자에 글이 있다면 예쁘게 양식에 맞춰 꺼내 보여줍니다.
System.out.println("번호 : " + foundArticle.getId());
System.out.println("작성날짜 : " + foundArticle.getRegDate());
System.out.println("수정날짜 : " + foundArticle.getUpdateDate());
System.out.println("제목 : " + foundArticle.getTitle());
System.out.println("내용 : " + foundArticle.getBody());
}
}
// =======================================================
// [6] 게시글 수정 (article modify)
// =======================================================
else if (cmd.startsWith("article modify ")) {
System.out.println("== 게시글 수정 ==");
// 1. 명령어 쪼개서 숫자(ID) 뽑아내기
String[] cmdBits = cmd.split(" ");
int id = Integer.parseInt(cmdBits[2]);
Article foundArticle = null;
// 찾은 게시글을 담을 빈 공간
// null = (초기 상태): 지금은 탐색을 시작하기 전이니까, 아무것도 없는 '빈손(null)' 상태이다.
// 숫자에서는 "없다"를 표현할 때 0이나 -1을 썼지만,
// 게시물(객체)처럼 덩치가 큰 데이터에서는 비었다는 것을 표현할 때 null 이라는 단어를 쓴다.
// 2. 리스트를 뒤져서 해당 ID를 가진 게시글 찾기
for (Article article : articles) {
if (article.getId() == id) {
foundArticle = article; // 찾았다면 빈 공간에 쏙!
break; // 찾았으니 반복문 탈출
}
}
// 3. 찾은 결과에 따라 다르게 처리하기
if (foundArticle == null) {
// 못 찾았을 때
System.out.printf("%d번 게시글은 없습니다.\n", id);
} else {
// 찾았을 때 (수정 진행)
// 3-1. 기존 내용 보여주기
System.out.println("기존 title : " + foundArticle.getTitle());
//자바에서 . (점, Dot)은 한국어로 "~의 안에 있는" 또는 **"~가 가지고 있는"**이라는 뜻이다.
//foundArticle: 조금 전 for문을 돌려서 찾아낸 다음, 쥐고 있는 게시글 전체(바구니)'
//foundArticle.getTitle()은 "내 손에 쥐고 있는 찾은 게시글(foundArticle)의 제목(title) 이라는 뜻이 된다.
System.out.println("기존 body : " + foundArticle.getBody());
// 3-2. 새로운 내용 입력받기
System.out.print("새 제목 : ");
String newTitle = sc.nextLine().trim();
System.out.print("새 내용 : ");
String newBody = sc.nextLine().trim();
// 3-3. 기존 게시글의 데이터 덮어쓰기 (★수정의 핵심★)
foundArticle.setTitle(newTitle);
foundArticle.setBody(newBody);
foundArticle.setUpdateDate(Util.getNowStr());
System.out.printf("%d번 게시글이 수정되었습니다.\n", id);
}
}