java 학습일기 day17 - 텍스트게시판 복습

이건구·2023년 9월 16일
0

텍스트게시판 1번에서 6번까지 빠르게 만들기 복습

1. 종료기능

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.print("명령어 : ");
            String command = sc.nextLine();
            if (command.equals("exit")) {
                break;
            }
        }
    }
}

변수 command에 입력받은값이 "exit"와 같다면 종료가되는 조건문을 만든다.

2. 게시물 추가

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    static int LastArticleNum = 0;
    static ArrayList<Article> articles = new ArrayList<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.print("명령어 : ");
            String command = sc.nextLine();
            if (command.equals("exit")) {
                break;
            } else if (command.equals("add")) {
                LastArticleNum++;
                System.out.print("게시물 제목을 입력해주세요 : ");
                String title = sc.nextLine();
                System.out.print("게시물 내용을 입력해주세요 : ");
                String content = sc.nextLine();
                Article article = new Article(LastArticleNum, title, content);
                articles.add(article);
                System.out.println("게시물이 추가되었습니다.");
            }
        }
    }
}
public class Article {
    private int id;
    private String title;
    private String content;
    public Article(int id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }
}

게시물 추가를 하면 게시물의 번호, 제목, 내용을 저장해야하니 Article의 클래스를 따로 만들어두고 그 객체들을 저장할 ArrayList를 만들어 리스트에 추가를해준다.

3. 게시물 조회

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    static int LastArticleNum = 0;
    static ArrayList<Article> articles = new ArrayList<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(true) {
            System.out.print("명령어 : ");
            String command = sc.nextLine();
            if (command.equals("exit")) {
                System.out.println("프로그램을 종료합니다");
                break;
            } else if (command.equals("add")) {
                LastArticleNum++;
                System.out.print("게시물 제목을 입력해주세요 : ");
                String title = sc.nextLine();
                System.out.print("게시물 내용을 입력해주세요 : ");
                String content = sc.nextLine();
                Article article = new Article(LastArticleNum, title, content);
                articles.add(article);
                System.out.println("게시물이 추가되었습니다.");
            } else if (command.equals("list")) {
                for (Article article : articles) {
                    System.out.println("번호 : " + article.getId());
                    System.out.println("제목 : " + article.getTitle());
                    System.out.println("내용 : " + article.getContent());
                    System.out.println("========================================");
                }
            }
        }
    }
}

강화된 for문으로 article articles에 저장된 객체들을 순회하며 출력문을 반복한다.

4. 게시물 수정

 else if (command.equals("update")) {
                while(true) {
                    System.out.print("수정할 게시물 번호 또는 \"back\"를 입력해주세요 : ");
                    String strNum = sc.nextLine();
                    if (strNum.equals("back")) {
                        break;
                    }
                    int num = convertInt(strNum);
                    boolean articleExist = false;
                    if (num == -1) {
                        System.out.println("숫자를 입력해주세요");
                    } else {
                        for (Article article : articles) {
                            if (article.getId() == num) {
                                System.out.print("새로운 제목 : ");
                                String newTitle = sc.nextLine();
                                System.out.print("새로운 내용 : ");
                                String newContent = sc.nextLine();
                                article.setTitle(newTitle);
                                article.setContent(newContent);
                                System.out.printf("%d번 게시물이 수정되었습니다.\n", num);
                                articleExist = true;
                            }
                        }
                    }
                    if (articleExist) {
                        break;
                    } else {
                        System.out.println("없는 게시물 번호입니다.");
                    }
                }
            }
        }
    }
    public static int convertInt(String strNum) {
        int num = -1;
        try {
            num = Integer.parseInt(strNum);
        } catch (NumberFormatException ignored) {
        }
        return num;
    }
}

여기서부터는 코드가 길어져서 추가및 수정한 부분만 올렸다.

list코드 바로 아래에 update와 일치한다면 수정할 게시물 번호를 받고 그 번호를 nextLine()으로 받았기때문에 convertInt() 라는 이름의 함수를 아래에 따로 만들어서 int로 변환해주는 작업을한다.

그 과정에서 int로 변환되지않는 값이 들어오게된다면 "숫자를 입력해주세요"라는 문구가 출력되게하고 다시 수정할 게시물 번호를 입력받도록 반복했다.

그리고 그외에 숫자가 입력되면 articles에 저장된 article들 안에 id들과 비교를하여 일치하는 id가 있다면 수정하도록했다.

해당 if문이 실행되면 articleExist를 true로 변경하고 true값이 밖에 나오게된다면 while반복문이끝나도록 break를 넣었다.

if문이 실행되지 않았다면 "없는 게시물 번호입니다"를 출력하고 다시 수정할 게시물 번호를 입력하도록 반복한다.

그리고 만약 수정하고싶은 게시물이 없다면 "back"를 입력하면 처음 명령어 입력받는 창으로 돌아가게했다.

5. 게시물 삭제

 else if (command.equals("delete")) {
                while(true) {
                    System.out.print("삭제 게시물 번호 또는 \"back\"를 입력해주세요 : ");
                    String strNum = sc.nextLine();
                    if (strNum.equals("back")) {
                        break;
                    }
                    int num = convertInt(strNum);
                    boolean articleExist = false;
                    if (num == -1) {
                        System.out.println("숫자를 입력해주세요");
                    } else {
                        for (Article article : articles) {
                            if (article.getId() == num) {
                                articles.remove(article);
                                articleExist = true;
                            }
                        }
                    }
                    if (articleExist) {
                        break;
                    } else {
                        System.out.println("없는 게시물 번호입니다.");
                    }
                }
            }

여기서부터는 위의 게시물 수정기능을 복사하여 "숫자를 입력해주세요"와 엮여있는 else문만 수정하면된다 그부분을 num과 일치하는 id값을 찾게되면 해당 article을 remove하면된다.

6. 상세보기 화면 만들기

 else if (command.equals("detail")) {
                while(true) {
                    System.out.print("상세보기 할 게시물 번호 또는 \"back\"를 입력해주세요 : ");
                    String strNum = sc.nextLine();
                    if (strNum.equals("back")) {
                        break;
                    }
                    int num = convertInt(strNum);
                    boolean articleExist = false;
                    if (num == -1) {
                        System.out.println("숫자를 입력해주세요");
                    } else {
                        for (Article article : articles) {
                            if (article.getId() == num) {
                                System.out.println("번호 : " + article.getId());
                                System.out.println("제목 : " + article.getTitle());
                                System.out.println("내용 : " + article.getContent());
                                System.out.println("========================================");
                                articleExist = true;
                            }
                        }
                    }
                    if (articleExist) {
                        break;
                    } else {
                        System.out.println("없는 게시물 번호입니다.");
                    }
                }
            }

게시물이 많아질수록 list에서 내용까지 보게된다면 가독성이 떨어지므로 list를 입력할땐 제목과 번호만 출력되도록 list코드에서 내용이 출력되는 출력문을 지운다.

그리고 코드를 다시 복사해오고 else문만 수정해준다.

사실상 게시물의 수정코드만 잘짜두면 나머지는 코드를 똑같이 사용한다.

0개의 댓글