본문 바로가기

강의

200507 - 게시판 만들기(코드)

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Board board = new Board();
board.setScanner(sc);
board.start();
sc.close();
}
}

class Board {
Scanner sc;
Article[] articles;
User[] user;
int signUpRecord;
int articlesLastIndex;
int nowLogIn;
boolean stateLogIn;

Board() {
nowLogIn = -1;
articlesLastIndex = -1; // 아무것도 입력되지 않은 상태
articles = new Article[100];
user = new User[10];
stateLogIn = false;
}

int getArticlesCount() {
return articlesLastIndex + 1;
}

void setScanner(Scanner sc) {
this.sc = sc;
}

void start() {
showHelp();

while (true) {
System.out.print("게시판) ");
String command = sc.next().trim();

if (command.equals("help")) {
sc.nextLine();
doCommandHelp();
} else if (command.equals("list")) {
sc.nextLine();
doCommandList();
} else if (command.equals("add")) {
sc.nextLine();
doCommandAdd();
} else if (command.equals("detail")) {
int idToDetail = sc.nextInt();
sc.nextLine();
doCommandDetail(idToDetail);
} else if (command.equals("delete")) {
int idToDelete = sc.nextInt();
sc.nextLine();
doCommandDelete(idToDelete);
} else if (command.equals("change")) {
sc.nextLine();
doCommandChange();
} else if (command.equals("signup")) {
sc.nextLine();
doCommandSignUp();
} else if (command.equals("login")) {
sc.nextLine();
doCommandLogIn();
} else if (command.equals("logout")) {
sc.nextLine();
doCommandLogOut();
} else if (command.equals("exit")) {
sc.nextLine();
doCommandExit();
break;
} else {
sc.nextLine();
System.out.println("일치하는 명령어가 없습니다.");
}
}
}

void doCommandLogOut() {
if(stateLogIn) {
while(true) {
System.out.print("로그아웃 하시겠습니까?(Y/N) : ");
char yesOrNo = sc.next().charAt(0);
if(yesOrNo=='Y') {
System.out.println("로그아웃 되었습니다.");
user[nowLogIn].login = false;
nowLogIn = -1;
stateLogIn = false;
break;
}
else if(yesOrNo=='N') {
System.out.println("로그아웃을 취소하였습니다.");
break;
}
else {
System.out.println("잘못된 입력입니다. 다시 입력해주세요.");
}
}
}
else {
System.out.println("현재 로그인 상태가 아닙니다.");
}
}

void doCommandLogIn() {
if(signUpRecord==0) {
System.out.println("현재 회원이 없습니다...");
}
else {
if(!stateLogIn) {
System.out.print("ID를 입력하세요 : ");
String inputId = sc.next().trim();
System.out.print("비밀번호를 입력하세요 : ");
String inputPw = sc.next().trim();
for(int i=0; i<signUpRecord; i++) {
if(user[i].userId.equals(inputId)) {
if(user[i].userPw.equals(inputPw)) {
//로그인 상태로 변경하고, 글 작성, 본인글 삭제/수정 권한 부여 
System.out.println("== 안녕하세요. "+user[i].userId +"님 ==");
user[i].login = true;
stateLogIn = true;
nowLogIn = i;
}
else {
System.out.println("잘못된 ID 혹은 PW 입니다.");
}
}
}
}
else {
System.out.println("이미 로그인 된 상태입니다.");
}
}
}

void doCommandSignUp() {
user[signUpRecord] = new User();
System.out.println("== 회원가입 ==");
System.out.print("가입할 아이디를 입력하세요.(공백불가) : ");
user[signUpRecord].userId = sc.next().trim();
System.out.print("비밀번호를 입력하세요.(공백불가) : ");
user[signUpRecord].userPw = sc.next().trim();
signUpRecord++;
}

// //추천은 어디서 받고 어디에 보여줄 생각?
// void doCommandRecommend(int idToRecommend) {
// System.out.println("== 게시물 추천 ==");
// if(articles[idToRecommend].id == 0) {
// System.out.println("해당 게시물은 존재하지 않습니다.");
// }
// else {
//
// }
// }

// // 조회수 기록 기준 : detail 확인 수.
// void doCommandHits() {
// System.out.println("== 게시물 조회수 기록 ==");
// if (articlesLastIndex == -1) {
// System.out.println("게시물이 존재하지 않습니다.");
// } else {
// for (int i = 0; i <= articlesLastIndex; i++) {
// System.out.printf("%d번 게시글의 조회수 : %d\n", articles[i].id, articles[i].hitsCount);
// }
// }
//
// }

void doCommandChange() {
if(!stateLogIn) {
System.out.println("게시물 수정에는 로그인이 필요합니다.");
return;
}
System.out.println("== 게시물 수정 ==");
if (articlesLastIndex == -1) {
System.out.println("게시물이 존재하지 않습니다.");
} else {
System.out.print("수정할 게시물의 번호 입력 ex)1 : ");
int changeNum = sc.nextInt();
sc.nextLine();
if(user[nowLogIn].login && nowLogIn==articles[changeNum].writeUserIdNum) {
if (changeNum >= 0 && changeNum <= articlesLastIndex + 1) {
System.out.print("제목 : ");
articles[changeNum - 1].title = sc.nextLine().trim();
System.out.print("내용 : ");
articles[changeNum - 1].body = sc.nextLine().trim();
articles[changeNum - 1].regDate = getNowDateStr();
articles[changeNum - 1].hitsCount = 0;
System.out.println(changeNum + "번 게시글이 수정되었습니다.");
} else {
System.out.println("해당 게시물은 존재하지 않습니다.");
}
}
else {
System.out.println("게시물 수정은 작성자 본인만 가능합니다.");
}
}
}

void doCommandDelete(int idToDelete) {
if(!stateLogIn) {
System.out.println("게시물 삭제에는 로그인이 필요합니다.");
return;
}
if(user[nowLogIn].login && nowLogIn==articles[idToDelete].writeUserIdNum) {
System.out.println("== 게시물 삭제 ==");
if (idToDelete > articlesLastIndex + 1 || idToDelete <= 0) {
System.out.println("해당 게시물은 존재하지 않습니다.");
} else {
for (int i = idToDelete - 1; i <= articlesLastIndex; i++) {
articles[i] = articles[i + 1];
// articles[i].id--;  //한번에 쓰면 오류가 나는 이유????
}
for (int i = idToDelete - 1; i < articlesLastIndex; i++) {
articles[i].id--;
}
articlesLastIndex--;
System.out.println(idToDelete + "번 게시물이 삭제되었습니다.");
}
}
else {
System.out.println("게시물 삭제는 작성자 본인만 가능합니다.");
}

}

void doCommandDetail(int idToDetail) {
System.out.println("== 게시물 상세 ==");
// 구현하기
if (idToDetail > articlesLastIndex + 1 || idToDetail <= 0) {
System.out.println("해당 게시물은 존재하지 않습니다.");
} else {
idToDetail -= 1;
System.out.println("번호 : " + articles[idToDetail].id);
System.out.println("날짜 : " + articles[idToDetail].regDate);
System.out.println("제목 : " + articles[idToDetail].title);
System.out.println("내용 : " + articles[idToDetail].body);
articles[idToDetail].hitsCount++;
recommend(articles[idToDetail]);
}
}

void recommend(Article article) {
System.out.print("해당 게시물을 추천하겠습니까?(yes) : ");
String yesOrNo = sc.next().trim();
if (yesOrNo.equals("yes")) {
article.recommendCount++;
System.out.println("해당 게시물을 추천하였습니다.");
} else {
System.out.println("해당 게시물을 추천하지 않았습니다.");
}
}

void doCommandAdd() {
if(stateLogIn) {
System.out.println("== 게시물 추가 ==");
// 구현하기
Article tempList = new Article();
tempList.writeUserIdNum = nowLogIn;
articlesLastIndex = getArticlesCount();
tempList.id = getArticlesCount();
System.out.print("제목 : ");
tempList.title = sc.nextLine().trim();
System.out.print("내용 : ");
tempList.body = sc.nextLine().trim();
tempList.regDate = getNowDateStr();
System.out.printf("%d번 글이 생성되었습니다.\n", tempList.id);
articles[articlesLastIndex] = tempList;
}
else {
System.out.println("글을 작성하기 위해선 로그인이 필요합니다.");
}
}

// 수정하면 조회수는 0.(안바뀌게 할 거면 Change 함수 수정)
void doCommandList() {
System.out.println("== 게시물 리스트 ==");
if (articlesLastIndex == -1) {
System.out.println("게시물이 존재하지 않습니다.");
} else {
//제일 긴 제목에 맞춰서 변경하는 거 나중에 해보기
// System.out.println("번호 | 날짜              | 제목 | 조회수 | 추천수");
System.out.printf("%3s | %17s | %8s | %3s | %5s\n", "번호", "날짜", "제목", "조회수", "추천수");
for (int i = 0; i <= articlesLastIndex; i++) {
System.out.printf("%5d | %15s | %10s | %6d | %6d\n", 
articles[i].id, articles[i].regDate, articles[i].title,
articles[i].hitsCount, articles[i].recommendCount);
// System.out.println((articles[i].id) + " | " + articles[i].regDate + " | " + articles[i].title + " | " + articles[i].hitsCount);
}
}
}

String getNowDateStr() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat Date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = Date.format(cal.getTime());
return dateStr;
}

void doCommandHelp() {
showHelp();
}

void showHelp() {
System.out.println("== 명령어 리스트 ==");
System.out.println("signup : 회원가입");
System.out.println("login : 로그인");
System.out.println("logout : 로그아웃");
System.out.println("===================");
System.out.println("help : 명령어 리스트");
System.out.println("list : 게시물 리스팅");
System.out.println("add : 게시물 추가");
System.out.println("delete {$게시물 번호} : 게시물 삭제");
System.out.println("change : 게시물 수정");
// System.out.println("hits : 게시물 조회수 기록");
System.out.println("exit : 종료");
System.out.println("detail {$게시물 번호} : 게시물 상세보기");
}

void doCommandExit() {
System.out.println("== 게시판 종료 ==");
}
}

class Article {
int id;
String regDate;
String title;
String body;
int hitsCount; // 조회수
int recommendCount;
int writeUserIdNum;
}
class User{
String userId;
String userPw;
boolean login;
User(){
login = false;
}
}