java 학습일기 day12 - java로 텍스트게시판 (1)

이건구·2023년 9월 11일
0

java학습일기

목록 보기
10/13

java로 텍스트 게시판만들기 (1)

요구사항 1) 루프종료

public class Main {
    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);

        while (true) {
            System.out.print("명령어 : ");
            String command = scan.nextLine();
            if (command.equals("exit")) {
                System.out.println("프로그램을 종료합니다.");
                break;
            }
        }
    }
}

조건이 true인 무한루프에서 종료를하려면 조건문을 만들고 함수 equals()에 (넣고싶은 종료 문구) exit를 넣었을때 동일한 문구가 들어온다면 break;로 종료를한다 break;는 반복문안에서 만날경우 해당 반복문을 바로 빠져나온다.

==============================================================================================

요구사항 2) 게시물추가

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

public class Mian {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        List<Article> articles = new ArrayList<>();

        int articleNum = 0;

        while (true) {
            System.out.print("명령어 : ");
            String command = sc.nextLine();
            if (command.equals("exit")) {
                System.out.println("프로그램을 종료합니다.");
                break;
            } else if (command.equals("add")) {
                articleNum++;
                System.out.print("게시물 제목을 입력해주세요 : ");
                String title = sc.nextLine();
                System.out.print("게시물 내용을 입력해주세요 : ");
                String content = sc.nextLine();

                Article article = new Article(articleNum, title, content);
                articles.add(articles.size(), article);

                System.out.println("게시물이 등록되었습니다.");

            }
        }
    }
}
class Article {
    int id;
    String title;
    String content;
    Article(int id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }

}

게시물을 추가할때 미리 배열의 갯수를 정해주지않아도 사용할수 있는 Arraylist를 사용했다.

그리고 조건문 add를 만들어 add라는 문구가 입력이되면 제목과 내용을 입력받는 함수를 만들고 그 내용을 Article타입의 객체를 새로 만들어 저장을한다.

그렇게 저장한 객체를 Arraylist에 순서대로 넣는다.

==============================================================================================

요구사항 3) 게시물 조회

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

public class Mian {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        List<Article> articles = new ArrayList<>();

        int articleNum = 0;

        while (true) {
            System.out.print("명령어 : ");
            String command = sc.nextLine();
            if (command.equals("exit")) {
                System.out.println("프로그램을 종료합니다.");
                break;
            } else if (command.equals("add")) {
                articleNum++;
                System.out.print("게시물 제목을 입력해주세요 : ");
                String title = sc.nextLine();
                System.out.print("게시물 내용을 입력해주세요 : ");
                String content = sc.nextLine();

                Article article = new Article(articleNum, title, content);
                articles.add(articles.size(), article);

                System.out.println("게시물이 등록되었습니다.");

            } else if (command.equals("list")) {
                for (int i = 0; i < articles.size(); i++) {

                    System.out.println("==================");
                    System.out.println("번호 : " + articles.get(i).id);
                    System.out.println("제목 : " + articles.get(i).title);
                }
            }
        }
    }
}

class Article {
    int id;
    String title;
    String content;

    Article(int id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }
}

else if로 list와 같은 문구를 입력을하면 Arraylist전체의 id와 제목을 출력하게함.

==============================================================================================

요구사항 4) 게시물 수정

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

public class Mian {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        List<Article> articles = new ArrayList<>();

        int articleNum = 0;

        while (true) {
            System.out.print("명령어 : ");
            String command = sc.nextLine();
            if (command.equals("exit")) {
                System.out.println("프로그램을 종료합니다.");
                break;
            } else if (command.equals("add")) {
                articleNum++;
                System.out.print("게시물 제목을 입력해주세요 : ");
                String title = sc.nextLine();
                System.out.print("게시물 내용을 입력해주세요 : ");
                String content = sc.nextLine();

                Article article = new Article(articleNum, title, content);
                articles.add(articles.size(), article);

                System.out.println("게시물이 등록되었습니다.");

            } else if (command.equals("update")) {
                System.out.printf("수정할 게시물 번호 : ");
                int number = sc.nextInt();
                sc.nextLine();
                boolean contentExist = false;
                for (int i = 0; i < articles.size(); i++) {
                    if (number == articles.get(i).id) {
                        System.out.printf("제목 : ");
                        String title = sc.nextLine();
                        System.out.printf("내용 : ");
                        String content = sc.nextLine();
                        Article article = new Article(number, title, content);
                        articles.set(i, article);
                        System.out.printf("%d번 게시물이 수정되었습니다\n", number);
                        contentExist = true;
                    }
                }
                if (contentExist == false) {
                    System.out.println("없는 게시물 번호입니다.");
                }
            } else if (command.equals("list")) {
                for (int i = 0; i < articles.size(); i++) {

                    System.out.println("==================");
                    System.out.println("번호 : " + articles.get(i).id);
                    System.out.println("제목 : " + articles.get(i).title);
                }
            }
        }
    }
}

class Article {
    int id;
    String title;
    String content;

    Article(int id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }
}

add와 list사이에 수정기능 update를 추가했다.

우선 update를 입력하면 수정할 게시물의 번호를 입력받게하고, 번호를 입력받으면 입력받은번호와 저장한 Arraylist안의 객체들내부에 id가 일치하는 객체를 찾고 그 객체를 set이라는 메서드로 수정을한다.

여기서 중요한건 반복문 바깥에 임의의 논리형변수 contentExist를 만들고 아래 조건문이 실행이된다면 true로 변경하도록 만들고 변경이 되지않았다면 Arraylist안에 동일한 게시물번호가 존재하지 않는것이니 false가 나온다면 "없는 게시물 번호입니다."가 출력되게한다.

==============================================================================================

요구사항 5) 게시물 삭제

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

public class Mian {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        List<Article> articles = new ArrayList<>();

        int articleNum = 0;

        while (true) {
            System.out.print("명령어 : ");
            String command = sc.nextLine();
            if (command.equals("exit")) {
                System.out.println("프로그램을 종료합니다.");
                break;
            } else if (command.equals("add")) {
                articleNum++;
                System.out.print("게시물 제목을 입력해주세요 : ");
                String title = sc.nextLine();
                System.out.print("게시물 내용을 입력해주세요 : ");
                String content = sc.nextLine();

                Article article = new Article(articleNum, title, content);
                articles.add(articles.size(), article);

                System.out.println("게시물이 등록되었습니다.");

            } else if (command.equals("update")) {
                System.out.printf("수정할 게시물 번호 : ");
                int number = sc.nextInt();
                sc.nextLine();
                boolean contentExist = false;
                for (int i = 0; i < articles.size(); i++) {
                    if (number == articles.get(i).id) {
                        System.out.printf("제목 : ");
                        String title = sc.nextLine();
                        System.out.printf("내용 : ");
                        String content = sc.nextLine();
                        Article article = new Article(number, title, content);
                        articles.set(i, article);
                        System.out.printf("%d번 게시물이 수정되었습니다\n", number);
                        contentExist = true;
                    }
                }
                if (contentExist == false) {
                    System.out.println("없는 게시물 번호입니다.");
                }
            } else if (command.equals("delete")) {
                System.out.printf("삭제할 게시물 번호 : ");
                int number = sc.nextInt();
                sc.nextLine();
                boolean contentExist = false;
                for (int i = 0; i < articles.size(); i++) {
                    if (number == articles.get(i).id) {
                        articles.remove(i);
                        System.out.printf("%d번 게시물이 삭제되었습니다\n", number);
                        contentExist = true;
                    }
                }
                if (contentExist == false) {
                    System.out.println("없는 게시물 번호입니다.");
                }
            } else if (command.equals("list")) {
                for (int i = 0; i < articles.size(); i++) {

                    System.out.println("==================");
                    System.out.println("번호 : " + articles.get(i).id);
                    System.out.println("제목 : " + articles.get(i).title);
                }
            }
        }
    }
}

class Article {
    int id;
    String title;
    String content;

    Article(int id, String title, String content) {
        this.id = id;
        this.title = title;
        this.content = content;
    }
}

삭제의 코드는 수정기능과 매우 비슷하다.

이번에도 번호를 입력받고 동일한번호가 있다면 contentExist를 true로 변경하고 이번엔 그 번호의 article을 remove()메서드로 제거를하면된다.

0개의 댓글