오늘보다 더 나은 내일의 나에게_

비전공자의 IoT 국비 교육 수강일지 Day_21~24 본문

비전공자의 코딩일지

비전공자의 IoT 국비 교육 수강일지 Day_21~24

chan_96 2022. 1. 20. 18:17
728x90

미니 프로젝트를 4일 동안 진행했다

 

자바오라클 데이터베이스를 통해 단어 퀴즈 만드는 프로그램을 팀 미니 프로젝트로 선정 후 진행하였다.

MVC패턴을 이용해 작성을 해야 하고 JDBC코드를 직접 작성해야 한다.


 

17일 - 주제 선정 후 오라클 데이터베이스 설정 및 기획서 및 문서작성

 

 

오라클 데이터베이스 서버와 연결 설정

Oracle SQL Developer로 학원 데이터베이스 서버와 연결 설정을 했다.

 

 

 

이클립스로 서버와 연결 설정

이클립스로 데이터베이스 연결 설정 진행!

 

이클립스 데이터베이스 connection 상태
이클립스 데이터베이스 connection 상태

이클립스 데이터베이스 connection 상태 표시 화면!

 

후에 팀원들과 문서 및 서류 기획서 작성과 github 저장소 연동 작업을 진행하였다.

github Organization 생성
github Organization 생성

프로젝트 저장공간을 나의 repository를 생성하려다가 Organization으로 생성하였다.

이유는 팀원들 모두 프로젝트를 동등하게 관리할 수 있고 한 명에게 의존적인 형태가 안되기 때문이다.

 

하지만... 과연 작업을 하면서 충돌 현상을 잘 해결할 수 있을지 의문이긴 하다... 나도 깃허브는 지금까지 혼자만 사용했기 때문에 충돌 현상과 오류가 뜨면 많이 당황스러울 것 같긴 하다.

그렇지만 어차피 언젠간 겪어야 하는 난관이고 빨리 맞닥뜨려 경험해보는 게 좋을 듯싶다!


 

18일 ~ 20일

18일 => 자바와 데이터베이스 연동, 패키지 및 코드 설계
19일 => 로직 구현, 수정, 검토 최종 정리
20일 => 발표 준비

 

유스 케이스 다이어그램

유스케이스 다이어그램 간략한 형태
유스케이스 다이어그램 간략한 형태

=> 게임 시작 시 로그인 회원가입 종료 3가지 목록이 있고 로그인 성공 시 게임하기, 누적 결과 보기, 랭킹 확인, 로그아웃 등 4가지 목록으로 구성되어있다.

 

 


 

테이블 목록

USER_INFO 테이블 조회
USER_INFO 테이블 조회
USER_INFO 테이블
USER_INFO 테이블

 

 

WORD_LIST 테이블은 연도별 2000년, 2010년, 2020년대의 단어와 뜻이 정리되어있다.

연도별로 약 20~30개 정도가 있다.

WORD_LIST 테이블 조회
WORD_LIST 테이블 조회
WORD_LIST 테이블
WORD_LIST 테이블

 


 

프로젝트 구성

Model 패키지

UserInfoVO 클래스
더보기
package Model;

public class UserInfoVO {

	// 필드 : 아이디, 비밀번호, 점수
	private String id;
	private String password;
	private int score;

	// 생성자
	public UserInfoVO() {}
	public UserInfoVO(String id, String password) {
		this.id = id;
		this.password = password;
		this.score = 0;
	}
	public UserInfoVO(String id, int score) {
		this.id = id;
		this.score = score;
	}

	// 메소드
	public String getID() {
		return id;
	}

	public String getPASSWORD() {
		return password;
	}

	public int getSCORE() {
		return score;
	}
}

UserInfoDAO 클래스
더보기
package Model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class UserInfoDAO {
	Connection conn = null;
	PreparedStatement pst = null;
	ResultSet rs = null;
	boolean check = false;

	public void connect() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");

			String url = "jdbc:oracle:thin:@project-db-stu.ddns.net:1524:xe";
			String user = "campus_d_5_0115";
			String password = "smhrd5";

			// 2. 사용할 계정 선택, db 연결 객체(Connection) 생성
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 사용한 객체들 반환(종료)
	public void close() {
		try {
			if (rs != null) {
				rs.close(); // selectStds(), selectOneStd()에서만 사용하는 객체
							// ResultSet 객체가 생성되었을때만 호출 가능한 메서드
			}
			if (pst != null) {
				pst.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 회원가입 기능
	public boolean insertUser(String id, String password) {

		try {
			// jdbc 드라이버 불러오기
			connect();

			String sql = "INSERT INTO USER_INFO VALUES(?, ?, ?)";
			pst = conn.prepareStatement(sql);
			pst.setString(1, id);
			pst.setString(2, password);
			pst.setInt(3, 0);

			int cnt = pst.executeUpdate();

			if (cnt > 0) {// 추가 성공
				check = true;
			} else { // 추가 실패
				check = false;
			}

		} catch (Exception e) {
			System.out.println("중복된 아이디거나 잘못된 형식입니다!");
		} finally {
			close();
		}
		return check;
	}// end of insertUser

	// 로그인 기능
	public boolean login(String id, String password) {
		boolean check1 = false;

		try {
			// jdbc 드라이버 불러오기
			connect();

			String sql = "SELECT ID, PASSWORD FROM USER_INFO";
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			
			while (rs.next()) {
				String get_id = rs.getString("ID");
				String get_password = rs.getString("PASSWORD");
				
				// 입력받은 id와 데이터베이스 id와 password 비교
				if (get_id.equals(id) && get_password.equals(password)) {
					check1 = true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
		return check1;
	}// end of login

	public void updateScore(int score, String id) {

		try {
			connect();

			String sql = "UPDATE USER_INFO SET SCORE = ? WHERE ID = ?";
			pst = conn.prepareStatement(sql);
			pst.setInt(1, score);
			pst.setString(2, id);

			pst.executeUpdate();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
	}


	// 데이터베이스에 점수가져오는 기능
	public int getScore(String id) {
		int score = 0;
		try {
			connect();

			String sql = "SELECT ID, SCORE FROM USER_INFO WHERE ID = ?";

			pst = conn.prepareStatement(sql);
			pst.setString(1, id);
			rs = pst.executeQuery();
			if (rs.next()) {
				String get_id = rs.getString("ID"); // 현재 커서가 가르키고 있는 행의 첫번째 컬럼값을 읽어오겠다!
				int get_score = rs.getInt("SCORE"); // 컬럼이름과 일치하게 작성

				// 입력받은 id와 데이터베이스 id와 password 비교
				if (get_id.equals(id)) {
					score = get_score;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
		return score;
	}

	// rank_분석
	public ArrayList<UserInfoVO> rank() {
		ArrayList<UserInfoVO> al = new ArrayList<UserInfoVO>();
		try {

			connect();

			String sql = "SELECT ID, SCORE FROM USER_INFO ORDER BY SCORE DESC";

			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			
			while(rs.next()) {
				String id = rs.getString("ID"); 
				int score = rs.getInt("SCORE");
				
				//위에서 읽어온 값들로 초기화시켜 생성한 UserInfoVO 객체의 참조값을
				//ArrayList에 추가
				al.add(new UserInfoVO(id, score));
				
			}
			

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close();
		}
		return al;
	}

}// end of class

 


WordListVO 클래스

더보기
package Model;

public class WordListVO {
	private String word;
	private String mean;
	private int year;
	private String hint1;
	private String hint2;

	public WordListVO(String word, String mean, int year, String hint1, String hint2) {
		this.word = word;
		this.mean = mean;
		this.year = year;
		this.hint1 = hint1;
		this.hint2 = hint2;
	}

	public String getWord() {
		return word;
	}

	public String getMean() {
		return mean;
	}

	public int getYear() {
		return year;
	}

	public String getHint1() {
		return hint1;
	}

	public String getHint2() {
		return hint2;
	}
}


WordListDAO 클래스

더보기
package Model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class WordListDAO {

	Connection conn = null;
	PreparedStatement pst = null;
	ResultSet rs = null;
	
	public void connect() {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			
			String url = "jdbc:oracle:thin:@project-db-stu.ddns.net:1524:xe";
			String user = "campus_d_5_0115";
			String password = "smhrd5";
			
			//2. 사용할 계정 선택, db 연결 객체(Connection) 생성
			conn = DriverManager.getConnection(url, user, password);			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	//사용한 객체들 반환(종료)
	public void close() {
		try {
			if(rs != null) {
				rs.close(); //selectStds(), selectOneStd()에서만 사용하는 객체				
							//ResultSet 객체가 생성되었을때만 호출 가능한 메서드
			}
			if(pst != null) {
				pst.close();				
			}
			if(conn != null) {
				conn.close();				
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
	
	//문제 뜻 불러오는 메소드
	public  ArrayList<WordListVO> wordList(int yearNum) {
		//jdbc 드라이버 불러오기
		connect();
		
		ArrayList<WordListVO> al = new ArrayList<WordListVO>();
		
		
		try {
			String sql = "SELECT * FROM WORD_LIST WHERE YEAR = ?";
			
			//4. sql 구문 준비 객체(PreparedStatement) 생성
			pst = conn.prepareStatement(sql);
			pst.setInt(1, yearNum);
			//5. sql문을 실행하고 결과 처리
			rs = pst.executeQuery();
			
			while(rs.next()) {
				
				String word = rs.getString("WORD"); //현재 커서가 가르키고 있는 행의 첫번째 컬럼값을 읽어오겠다!
				String mean = rs.getString("MEAN"); //컬럼이름과 일치하게 작성
				int year = rs.getInt("YEAR");
				String hint1 = rs.getString("HINT1");
				String hint2 = rs.getString("HINT2");
				
				//위에서 읽어온 값들로 초기화시켜 생성한 WordListVO 객체의 참조값을
				//ArrayList에 추가
				al.add(new WordListVO(word, mean, year, hint1, hint2));
				
			}
		}catch (Exception e){
			e.printStackTrace();
		}finally {
			close();
		}
		return al;
	}
}



View 패키지

ViewMain 클래스
더보기
package View;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

import Controller.GameStartController;
import Model.UserInfoDAO;
import Model.UserInfoVO;
import Model.WordListDAO;
import Model.WordListVO;
import javazoom.jl.player.MP3Player;

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

		Scanner sc = new Scanner(System.in);
		UserInfoDAO userDAO = new UserInfoDAO();
		WordListDAO wordDAO = new WordListDAO();

		// 컨트롤러 객체 생성
		GameStartController con = new GameStartController();

		// MP3Player 사용하기 위해 가장먼저해야할일!
		MP3Player mp3 = new MP3Player();

		mp3.play("C:\\시작bgm.mp3");

		System.out.println("           ∧_∧     ");
		System.out.println("          (*・∀・*)     ");
		System.out.println("     ★*。。:゚*〇☆〇*゚:。。:*★");
		System.out.println("     ☆。。*・:+*゚   ゚*+:・*。。☆");
		System.out.println("     ▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀ ");
		System.out.println("           년  도  별      ");
		System.out.println("          문 제 맞 추 기    ");
		System.out.println("             게   임       ");
		System.out.println("     ▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀▄▀");
		System.out.println("");
		System.out.println("");

		while (true) {
			System.out.println("     ╔═════ °• ♔ •° ═════╗ ");
			System.out.println("            ①.회원가입       ");
			System.out.println("            ②.로그인        ");
			System.out.println("            ③.종료         ");
			System.out.println("     ╚═════ °• ♔ •° ═════╝");
			System.out.print("       번호선택 >>>>  ");

			int choice = sc.nextInt();
			
			if (choice == 1) { // 회원가입
				System.out.println("");
				System.out.println("");
				System.out.println("   ☆★‿︵‿︵ʚ˚̣̣̣͙ɞ・회 원 가 입 중ʚ˚̣̣̣͙ɞ‿︵‿︵ ☆★");
				System.out.print("         ID : ");
				String id = sc.next();
				System.out.print("         PW : ");
				String pw = sc.next();
				
				boolean check = userDAO.insertUser(id, pw); // boolean true나 false

				if (check) {
					System.out.println("");
					System.out.println("      아이디 생성 성공 ⁽⁽٩( ᐖ )۶⁾⁾");

				} else {
					System.out.println("");
					System.out.println("      아이디 생성 실패 (ˋ⌒T) ");

				}
				System.out.println();
			} else if (choice == 2) { // 로그인
				boolean check = false;
				System.out.println("");
				System.out.println("");
				System.out.println(" ☆★‿︵‿︵‿︵ʚ˚̣̣̣͙ɞ・로 그 인 중ʚ˚̣̣̣͙ɞ‿︵‿︵‿︵ ☆★");
				System.out.print("         ID : ");
				String id = sc.next();
				System.out.print("         PW : ");
				String password = sc.next();
				
				check = userDAO.login(id, password);
				System.out.println();

				if (check) {
					
					if(mp3.isPlaying()) {
						mp3.stop();			
					}
					
					System.out.println("      로그인 성공 ⁽⁽٩( ᐖ )۶⁾⁾");

					System.out.println();

					while (true) {
						System.out.println("     ╔═════ °• ♔ •° ═════╗ ");
						System.out.println("            ①.게임하기       ");
						System.out.println("            ②.누적결과       ");
						System.out.println("            ③.랭킹확인       ");
						System.out.println("            ④.로그아웃       ");
						System.out.println("     ╚═════ °• ♔ •° ═════╝");
						System.out.print("       번호선택 >>>>  ");
						int num = sc.nextInt();
						System.out.println();

						if (num == 1) {// 게임하기
							

							System.out.println("");
							System.out.println("     ╭ ⁀ ⁀ ╮");
							System.out.println("     ( '👅' )~ ① 2000년대");
							System.out.println("     ╰ ‿ ‿ ╯");
							System.out.println("                       ╭ ⁀ ⁀ ╮");
							System.out.println("              ② 2010년대 ~( '👅' )");
							System.out.println("                       ╰ ‿ ‿ ╯");
							System.out.println("     ╭ ⁀ ⁀ ╮");
							System.out.println("     ( '👅' )~ ③ 2020년대");
							System.out.println("     ╰ ‿ ‿ ╯");
							System.out.print("       번호선택 >>>>  ");
							int yearNum = sc.nextInt();

							
							System.out.println();
							if (yearNum == 1) {// 2000년대
								// 게임시작호출
								con.start(2000, id);
							} else if (yearNum == 2) {// 2010년대
								// 게임시작호출
								// 2010년대
								con.start(2010, id);

							} else if (yearNum == 3) {// 2020년대
								// 게임시작호출
								// 2020년대
								con.start(2020, id);

							} else {
								System.out.println("잘못 입력!!");
							}

						} else if (num == 2) {// 누적결과보기
							int totalScore = userDAO.getScore(id);
							System.out.println(totalScore + "점 입니다.!");

							if (totalScore > 80) {
								// 효과음 출력
								mp3.play("C:\\80점.mp3");

								System.out.println("⊂_ ヽ、");
								System.out.println("  \\ Λ_Λ");
								System.out.println("   \( ‘ㅅ’ ) 두둠칫");
								System.out.println("    > ⌒ヽ");
								System.out.println("   /   へ\");
								System.out.println("   /  / \\");
								System.out.println("   レ ノ   ヽ_つ");
								System.out.println("  / /두둠칫");
								System.out.println("  / /|");
								System.out.println(" ( (ヽ");
								System.out.println(" | |、\");
								System.out.println(" | |  ) /");
								System.out.println("`ノ )  Lノ");
								System.out.println("");
								System.out.println("시대를 아우르는 당신!! 유행어의 마스터 이시군요!");

							} else if (totalScore > 60) {
								// 효과음 출력
								mp3.play("C:\\60점.mp3");

								System.out.println("      ∧_∧");
								System.out.println("    (´・ω・)つ_  ∧");
								System.out.println("     (つ  / (・ω・。)");
								System.out.println("      しーJ (nnノ)");
								System.out.println("");
								System.out.println(" 그래도 노력하는 당신..쫌만 더 열심히 하세요!");

							} else if (totalScore > 40) {
								// 효과음 출력
								mp3.play("C:\\40점.mp3");

								System.out.println(" ༼ ºل͟º ༼ ºل͟º ༼ ºل͟º ༽ ºل͟º ༽ ºل͟º ༽");
								System.out.println("");
								System.out.println("조금 더 유행어 공부를 해보시는게 어떤가요?");

							} else {
								// 효과음 출력
								mp3.play("C:\\0점.mp3");

								System.out.println(" ┏━━━━━┓ ");
								System.out.println("┃      ┃ ");
								System.out.println("┃ ┏ ━┓ ┃");
								System.out.println("┗━┛  ┃ ┃");
								System.out.println("   ┏━┛ ┃");
								System.out.println("   ┃ ┏━┛");
								System.out.println("   ┗━┛ ");
								System.out.println("  ┏━┓ ");
								System.out.println("  ┃ ┃ ");
								System.out.println("  ┗━┛  ");
								System.out.println("    〇 ");
								System.out.println("    o  ");
								System.out.println("     (・д・) ");
								System.out.println("");
								System.out.println("당신은 문제를 읽어보긴하셨나요?");
							}
							System.out.println();
						} else if (num == 3) {// 랭킹확인
							// 1.모든 사용자 출력 점수에 따라 정렬 후 출력
							System.out.println("      +*.。゚ ・*・:*:。*+。*。:゚+");
							System.out.println("     \\ヽ ٩( 'ω' )و ///");
							System.out.println("     ( ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄)");
							System.out.println("       world Ranking");
							System.out.println("(      ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄)");

							ArrayList<UserInfoVO> rank = userDAO.rank();
							
							for (int i = 0; i < 10; i++) {
								System.out.print((i + 1) + "위 아이디 : " + rank.get(i).getID());
								System.out.print("\t\t점수 : " + rank.get(i).getSCORE());
								System.out.println();
							}
							System.out.println();

						} else if (num == 4) {// 로그아웃
							// 로그아웃 효과음 출력
							mp3.play("C:\\종료.mp3");

							System.out.println("      ∧_∧");
							System.out.println("     (・ω・ )");
							System.out.println("     o┳o )");
							System.out.println("     ◎┻し'◎ ≡");
							System.out.println("     로그아웃 ...");
							System.out.println("");
							break;
						} else {
							System.out.println("    ☆★잘못입력 1부터 4사이 숫자입력☆★");
						}
					}

				} else {
					System.out.println("    ☆★로그인 실패!!☆★");
				}

			} else if (choice == 3) { // 종료
				System.out.println("       \\BYE//");
				System.out.println("      ∧_ヘ    ヘ_∧ ");
				System.out.println("     (/ω・)人(・ω\ ) ");
				System.out.println("     /` /   \ `\");
				mp3.play("C:\\종료.mp3");
				break;
			} else { // 잘못입력
				System.out.println("    ☆★잘못 입력!!☆★");
			}

		} // end of while
	}// end of main
}// end of class



Controller 패키지

GameStartController 클래스
더보기
package Controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

import Model.UserInfoDAO;
import Model.WordListDAO;
import Model.WordListVO;
import javazoom.jl.player.MP3Player;

public class GameStartController {
	
	//게임 시작 메서드
	public static void start(int yearNum, String id) {
		Scanner sc = new Scanner(System.in);
		UserInfoDAO userDAO = new UserInfoDAO();
		WordListDAO wordDAO = new WordListDAO();
		MP3Player mp3 = new MP3Player();

		// 2000년대

		ArrayList<WordListVO> vo = wordDAO.wordList(yearNum);
		int score = 0; // 문제 점수

		// vo객체(데이터베이스의 단어뜻) 인덱스값 랜덤을 정렬시킴
		Collections.shuffle(vo);

		System.out.println("      ∧_∧");
		System.out.println("     (`・ω・´ ) 三");
		System.out.println("     O┳〇 )");
		System.out.println("     ◎し◎- 三 ");
		System.out.println("     " + yearNum + "년대로 가는 중...");
		System.out.println("");
		
		// 게임시작시 효과음 재생
		mp3.play("C:\\게임시작.mp3");
		for (int i = 0; i < 5; i++) {

			// 문제출력
			System.out.println("   ════════════════════•°• ⚠ •°•════════════════════");
			System.out.println("     Q. " + vo.get(i).getMean());
			System.out.println("   ════════════════════•°• ⚠ •°•════════════════════");

			// 힌트점수누적
			int hintScore = 0;
			// 힌트 본 횟수
			int hintCnt = 0;

			while (true) {
				// 힌트보기 선택지 주기? 1번 정답입력 2번 힌트보기
				System.out.println();
				System.out.println("            ①.정답입력       ");
				System.out.println("            ②.힌트보기       ");
                System.out.println();
				System.out.print("       번호선택 >>>>  ");


				int num3 = sc.nextInt();
				
				if (num3 == 1) {
					// 답 입력
					System.out.print("       정답입력 >>>> ");
					String str = sc.next();

					if (vo.get(i).getWord().equals(str)) {

						// 점수추가
						score += 10 - hintScore;
						System.out.println();
						System.out.println("          .^   ^");
						System.out.println("          \\(>~<)/");
						System.out.println("           ( . ) ");
						System.out.println("           /    \\_");
						System.out.println("             정답!");
						System.out.println();

						// 정답 맞췄을때 효과음 출력
						mp3.play("C:\\정답.mp3");
						System.out.println();
						break;

					} else {
						System.out.println();
						System.out.println("         ╭┈ ↷");
						System.out.println("         │     정답은");
						System.out.println("         │    ┆ " + vo.get(i).getWord() + "입니다.");
						System.out.println("         ╰──────────────────────────────────────⠀⠀");

						// 정답 틀렸을때 효과음 출력
						mp3.play("C:\\오답.mp3");
						System.out.println();
						break;
					}

				} else if (num3 == 2) {
					if (hintCnt == 0) {
						// 힌트 1번 출력
						System.out.println();
						System.out.println("              첫번째 힌트 입니다!!");
						System.out.println("         | ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄|");
						System.out.println("\t\t\t" + vo.get(i).getHint1());
						System.out.println("         |_________________|");
						System.out.println("                ᕱ ᕱ ||");
						System.out.println("                ( ・ω・ ||");
						System.out.println("                / つΦ");
						hintCnt++;
						hintScore += 3;
					} else if (hintCnt == 1) {
						System.out.println();
						System.out.println("              두번째 힌트 입니다!!");
						System.out.println("          모든힌트를 다 보셨습니다!!");
						System.out.println("         | ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄|");
						System.out.println("\t\t\t" + vo.get(i).getHint2());
						System.out.println("         |_________________|");
						System.out.println("                ᕱ ᕱ ||");
						System.out.println("                ( ・ω・ ||");
						System.out.println("                / つΦ");
						hintCnt++;
						hintScore += 2;
					} else {
						System.out.println();
						System.out.println("         힌트를 다보셨습니다 ┐( ̄ヘ ̄)┌");
						System.out.println();
					}
				} else {
					System.out.println();
					System.out.println("      ☆★잘못입력 1 또는 2로 입력☆★");
					System.out.println();
				}
			}
		} // end of for문
		int totalScore = userDAO.getScore(id);
		userDAO.updateScore(totalScore + score, id);
		System.out.println("        /)⋈/)");
		System.out.println("       (。•ㅅ•。)♡");
		System.out.println("      ┏--∪-∪━━━━━┓");
		System.out.println("      " + score + "점 입니다");
		System.out.println("       ♡        *.。♡");
		System.out.println("      ┗-━━━━━━━┛");

		// 문제가 끝나고 효과음 출력
		mp3.play("C:\\문제끝.mp3");
		System.out.println();
	}
}

 

주요 기능 코드 설명

 

DB 연결하는 부분을 따로 메서드로 중복되는 코드를 최소화!

DB연결 connect() 메서드 분리
DB연결 connect() 메서드 분리

 

사용한 객체 반환하는 메서드로 중복 코드 최소화!

사용한 객체를 닫아주기위한 close() 메서드 분리
사용한 객체를 닫아주기위한 close() 메서드 분리

 

 


회원가입 기능을 가진 inserUser( ) 메서드이다. 

사용자에게 id와 password를 받아와 user_info테이블에 알맞은 순서로 값을 넣어준다

3개의 "?"의 번째 물음표는 id 두 번째는 password 3번째는 점수이다! 점수 같은 경우에는 회원가입을 할 때 0으로 초기화시켜줘야 해서 0을 대입해준다!

회원가입 기능의 insertUser 메소드
회원가입 기능의 insertUser( ) 메소드

 


 

 

로그인 기능을 수행해주는 login( ) 메서드이다.

먼저 DB의 USER_INFO 테이블의 id, 와 password의 모든 값을 가져온다.

가져온 값들과 사용자에게 입력받은 id와 password가 일치하는지 비교하고

일치하면 check1 변수를 true 변경하고, 그렇지 않으면 false값인 check1 변수를 리턴해준다.

 

글을 정리하면서 보완할 부분을 발견했다.

select 쿼리문에서 DB의 모든 id, 와 password를 가져오는데 전부 가져오지 말고 where 절을 써서 사용자에게 입력받은 id와 password를 조건으로 추가해주면 훨씬 효율적인 코드가 될 듯하다

보완한 코드
String sql = "SELECT ID, PASSWORD FROM USER_INFO WHERE ID = ? AND PASSWORD = ?";
pst = conn.prepareStatement(sql);
pst.setString(1, id);
pst.setString(2, password);
rs = pst.executeQuery();

if(rs.next()) {
    check1 = true;
}​


 

로그인 기능의 login 메소드
로그인 기능의 login( ) 메소드

 


 

문제를 다 풀었을 때 획득한 점수를 데이터베이스의 추가시키는 updateScore( ) 메서드이다.

이 부분을 만들면서 꽤나 시간을 많이 소비했다. updateScore라는 메서드를 만드는 시간은 얼마 안 걸렸다.

현재 로그인 중인 아이디의 DB의 SCORE 칼럼의 값이 첫 번째 게임 후 점수는 잘 변경되었지만 그 이후 누적되지 않고 한번 게임한 점수만 저장되었다. 이것저것 수정도 해보고 코드도 바꿔보고 했지만 이유는 간단했다. 

 

updateScore메서드를 호출하는 부분에서 문제를 풀기 전에 있던 점수와 문제를 풀고난 후의 점수를 더해주면 되었다.

더보기

totalScore에 문제를 풀기전에 DB에 저장된 점수를 불러와 저장!

score변수는 문제를 풀면서 얻은 점수!

 

updateScore( ) 메서드를 호출해 score와 totalScore를 더해주면 점수가 누적된다!!

 

getScore메서드는 밑에서 설명!


DB의 점수를 변경하는 updateScore 메서드
DB의 점수를 변경하는 updateScore 메서드

 


 

DB에서 현재 로그인 중인 id의 점수를 가져오는 getScore( ) 메서드!

select문에 현재 로그인 중인 id값을 조건에 넣어 DB 조회 후 rs객체에 담는다.

점수를 가져와 변수에 담고 반환시켜준다.

 

getScore( ) 메서드에서도 불필요한 조건문과 불필요한 코드를 발견했다.
작성할 때는 몰랐는데 기능을 다시 한번 살펴보면서 정리하니 코드를 작성할 때 보이지 않던 부분들이 많이 보이는 것 같다.

먼저 select문에서 이미 로그인된 id의 값을 조건으로 score를 가져왔는데 밑에서 또 조건문에 사용자가 입력한 id와 select문에서 가져온 id가 일치하는지 비교하는데 이 부분은 불필요하다!
같은 조건을 두 번 사용하는 것과 같다!
 
이 부분을 보완한 코드이다.
불필요한 조건 부분을 지우고 간략하게 수정이 가능하다!
더보기
String sql = "SELECT ID, SCORE FROM USER_INFO WHERE ID = ?";

pst = conn.prepareStatement(sql);
pst.setString(1, id);
rs = pst.executeQuery();

if (rs.next()) {
    score = rs.getInt("SCORE"); // 컬럼이름과 일치하게 작성
}

 

현재 로그인 중인 ID의 점수를 DB에서 불러오는 getScore 메소드
현재 로그인 중인 ID의 점수를 DB에서 불러오는 getScore 메소드

 

 


 

DB에 있는 SCORE 값을 내림차순으로 보기 위한 rank( ) 메서드이다.

아이디와 점수를 보여주기 위해서 ArrayList의에 값을 넣어준다.

DB의 USER_INFO 테이블은 크기가 정해져 있지 않아 배열의 크기가 가변적이어야 한다. 그래서 ArrayList를 사용해 id와 score값을 담아 반환시켜준다.

 

DB의 score점수를 내림차순으로 정렬시켜 id와 score를 ArrayList에 담아 반환 시키는 메서드
DB의 score점수를 내림차순으로 정렬시켜 id와 score를 ArrayList에 담아 반환 시키는 메서드

 


 

게임을 시작했을 때 WORD_LIST테이블의 연도에 맞는 값들을 가져와 반환해주는 wordList( ) 메서드이다.

매개변수로 2000, 2010, 2020 중 하나의 값을 받아와 select문 year 조건절에 추가해 DB를 조회 한 값들을 rs 객체에 담아준다. 마찬가지로 ArrayList에 rs에서 가져온 값들을 넣어주고 반환시킨다.

WORD_LIST테이블의 연도에 맞는 값들을 가져와 반환
WORD_LIST테이블의 연도에 맞는 값들을 가져와 반환

 

콘솔 동작 화면

콘솔창 사진1
콘솔창 사진1

 

콘솔창 사진2
콘솔창 사진2

 

 


 

Lauch4j로 exe파일로 만들었는데 문제가 계속 발생하였다.

첫 번째 문제

특수문자가?로 깨져서 표시됨...

특수문자가 깨짐
특수문자가 깨짐

두 번째

여자 저차 수정해서 특수문자가 깨지지 않도록 했는데 이제는 입력받는 한글 값이 제대로 인식이 안됨..

한글인식문제
한글인식문제

 

> 결국 결과물을 보여줄 수 있는 방법은 콘솔 창으로 보여주는 방법 이외엔 없는 듯하다.

 


콘솔 동작 영상

년도별 문제맞추기 게임 실행 화면

 

 

 

728x90
Comments