[텍스트 게시판] 5단계 - 명언 목록 출력

이다혜·2023년 10월 26일
0

Java 텍스트 게시판

목록 보기
5/17

요구사항


  1. 종료 입력시 종료
  2. 등록 입력시 명언 등록
  3. 등록시 생성된 명언 번호 출력
  4. 등록할 때마다 명언번호 증가
  5. 목록 입력시 현재까지 생성된 명언 목록 출력
  6. 명언번호로 명언 삭제
  7. 존재하지 않는 번호로 삭제 시도시 예외 처리
  8. 명언 수정
  9. 파일을 통한 영속성
  10. json 파일 빌드

Code


  • 객체 여러개를 유지하기 위해서는 명언 class를 생성하고 list에 저장해야 한다.
  • 생성자를 사용하여 입력받은 명언과 작가, 명언 번호를 초기화한다.

Quotation.java

public class Quotation {
    int id;
    String content;
    String author;

    public Quotation(int id, String content, String author) {
        this.id = id;
        this.content = content;
        this.author = author;
    }
}

App.java

class App {
    void run() {
        System.out.println("== 명언 앱 ==");

        ArrayList<Quotation> quotations = new ArrayList<>();
        int lastQuotationId = 0;

        while (true) {
            System.out.print("명언) ");

            Scanner sc = new Scanner(System.in);
            String cmd = sc.nextLine();

            if (cmd.equals("종료")) {
                break;
            } else if (cmd.equals("등록")) {
                System.out.print("명언 : ");
                String content = sc.nextLine();

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

                lastQuotationId++; // 명언 번호 증가
                int id = lastQuotationId;

                Quotation quotation = new Quotation(id, content, author); // 명언 객체 생성

                quotations.add(quotation); // 명언 list에 추가

                System.out.printf("%d번 명언이 등록되었습니다.\n",  lastQuotationId);
            } else if (cmd.equals("목록")) {
                System.out.println("번호 / 작가 / 명언");
                System.out.println("------------------");

                for(Quotation quotation : quotations) {
                    System.out.printf("%d / %s / %s\n", quotation.id, quotation.author, quotation.content);
                }
            }
        }
    }
}

실행 결과


0개의 댓글