우리가 메서드를 하나 만들건데, 어떤걸 만들거냐면 ! 게시글 찾아주는 일을 하는 메서드를 만들거야. 게시글을 특정 게시글을 수정하거나 상세보기를 할 때 계속 반복문을 돌면서 일일이 찾아줬는데 그냥 메서드로 찾는일을 하는 전문가를 데려오는거지
private static Article getArticleById(int id) {
for (Article article : articles) {
if (article.getId() == id) {
return article;
}
}
return null;
}
이렇게 메서드로 따로 빼두면 찾을 일이 있을 때 Article foundArticle = getArticleById(id); 이것만 쓰기만하면 끝난다니까? 이건 꼭해야 해..
게시글에 검색기능이 없으면 말이 안되겠지? 얼른 해보자!
먼저 list 출력하는 부분에서 검색기능을 추가 할거야.
String searchKeyword = cmd.substring("article list".length()).trim();
List<Article> forPrintArticles = articles;
if (searchKeyword.length() > 0) {
System.out.println("검색어 : " + searchKeyword);
forPrintArticles = new ArrayList<>();
for (Article article : articles) {
if (article.getTitle().contains(searchKeyword)) {
forPrintArticles.add(article);
}
}
if (forPrintArticles.size() == 0) {
System.out.println("검색 결과 없음");
continue;
}
}
-ArrayList형태로 forPrintArticles라는 새로운 리스트를 만들고 여기에 articles라는 값을 집어 넣을거야.
그리고 이제 찾아야되는데 만약 아까만든 searchKebord변수 에 저장되어있는 값의 길이가 0이상이면 뭐라도 있다는거잖아?! 그러면 그 결과를 저장할 새로운 리스트를 만드는거지! 이해됐니...
아니요..
그리고 for article을 순회 하면서 우리가 검색한 값이 article 제목에 포함 되어있으면? forPrintArticles에 add로 추가하는거야!
그리고.. 뭐.. size가 0이면 값은 없는거지..
System.out.println(" 번호 / 날짜 / 제목 / 내용 ");
for (int i = forPrintArticles.size() - 1; i >= 0; i--) {
Article article = forPrintArticles.get(i);
if (Util.getNowStr().split(" ")[0].equals(article.getRegDate().split(" ")[0])) {
System.out.printf(" %d / %s / %s / %s \n", article.getId(), article.getRegDate().split(" ")[1], article.getTitle(), article.getBody());
} else {
System.out.printf(" %d / %s / %s / %s \n", article.getId(), article.getRegDate().split(" ")[0], article.getTitle(), article.getBody());
}
}
이제 회원가입 기능을 만들거야! 그러면 아이디도 중복 체크해야되고 비밀번호도 확인해야하니까 약간 좀 이제 게시글 느낌이 나려나 ㅎㅎ
private static boolean isJoinableLoginId(String loginId) {
for (Member member : members) {
if (member.getLoginId().equals(loginId)) {
return false;
}
}
return true;
}
if (cmd.equals("member join")) {
System.out.println("==회원가입==");
int id = lastMemberId + 1;
String regDate = Util.getNowStr();
String loginId = null;
while (true) {
System.out.print("로그인 아이디 : ");
loginId = sc.nextLine().trim();
if (isJoinableLoginId(loginId) == false) {
System.out.println("이미 사용중이야");
continue;
}
break;
}
String password = null;
while (true) {
System.out.print("비밀번호 : ");
password = sc.nextLine().trim();
System.out.print("비밀번호 확인: ");
String passwordConfirm = sc.nextLine().trim();
if (password.equals(passwordConfirm) == false) {
System.out.println("비번 확인해");
continue;
}
break;
}
System.out.print("이름 : ");
String name = sc.nextLine().trim();
Member member = new Member(id, regDate, loginId, password, name);
members.add(member);
System.out.println(id + "번 회원이 가입되었습니다");
lastMemberId++;
}