요구사항
종료 입력시 종료
등록 입력시 명언 등록
등록시 생성된 명언 번호 출력
등록할 때마다 명언번호 증가
- 목록 입력시 현재까지 생성된 명언 목록 출력
- 명언번호로 명언 삭제
- 존재하지 않는 번호로 삭제 시도시 예외 처리
- 명언 수정
- 파일을 통한 영속성
- 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);
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);
}
}
}
}
}
실행 결과