diff --git a/Project/build.gradle b/Project/build.gradle new file mode 100644 index 0000000..c4f3a6c --- /dev/null +++ b/Project/build.gradle @@ -0,0 +1,23 @@ +plugins { + id 'java' +} + +group 'org.example' +version '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.1' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.1' + implementation 'mysql:mysql-connector-java:8.0.30' + implementation 'org.springframework.boot:spring-boot-starter-jdbc:2.7.4' + implementation 'org.springframework.boot:spring-boot-starter-test:2.7.4' + implementation 'org.springframework.boot:spring-boot-starter-web:2.7.4' +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/Project/gradlew b/Project/gradlew new file mode 100644 index 0000000..1b6c787 --- /dev/null +++ b/Project/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/Project/gradlew.bat b/Project/gradlew.bat new file mode 100644 index 0000000..107acd3 --- /dev/null +++ b/Project/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/Project/settings.gradle b/Project/settings.gradle new file mode 100644 index 0000000..3d0cdf1 --- /dev/null +++ b/Project/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'lion' + diff --git a/Project/src/main/java/Date10_12/FileController.java b/Project/src/main/java/Date10_12/FileController.java new file mode 100644 index 0000000..e52a40a --- /dev/null +++ b/Project/src/main/java/Date10_12/FileController.java @@ -0,0 +1,38 @@ +package Date10_12; + +import Date10_12.pasrser.Parser; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class FileController { + String filename = "C:\\DB file\\seoul_hospital_information.txt"; + Parser parser; + boolean isRemoveColumnName = true; + + public FileController(Parser parser) { + this.parser = parser; + } + + public FileController(Parser parser, boolean isRemoveColumnName) { + this.parser = parser; + this.isRemoveColumnName = isRemoveColumnName; + } + + List readLines() throws IOException { + List result = new ArrayList<>(); + BufferedReader br = new BufferedReader(new FileReader(filename)); + String str; + if (isRemoveColumnName) { + br.readLine(); + } + while ((str = br.readLine()) != null) { + result.add(parser.parse(str)); + } + return result; + } + +} diff --git a/Project/src/main/java/Date10_12/Main.java b/Project/src/main/java/Date10_12/Main.java new file mode 100644 index 0000000..62b96ff --- /dev/null +++ b/Project/src/main/java/Date10_12/Main.java @@ -0,0 +1,24 @@ +package Date10_12; + +import Date10_12.domain.Hospital; +import Date10_12.pasrser.HospitalParser; + +import java.io.IOException; +import java.sql.SQLException; +import java.util.List; + +public class Main { + public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException { + FileController hospitalLineReader = new FileController<>(new HospitalParser()); + + List hospitals = hospitalLineReader.readLines(); // 파일에서 값을 1줄씩 전체 읽어 list에 저장 + + HospitalParser hospitalParser = new HospitalParser(); + /* hospitalParser.CreateFile(); // 파일 생성 + + hospitalParser.Filewrite(hospitals); + hospitalParser.DBFilewrite(hospitals); + */ + hospitalParser.insert(hospitals); + } +} diff --git a/Project/src/main/java/Date10_12/dao/UserDao.java b/Project/src/main/java/Date10_12/dao/UserDao.java new file mode 100644 index 0000000..258cc8c --- /dev/null +++ b/Project/src/main/java/Date10_12/dao/UserDao.java @@ -0,0 +1,63 @@ +package Date10_12.dao; + +import Date10_12.domain.User; + +import java.sql.*; +import java.util.Map; + +public class UserDao { + + static Map env = System.getenv(); // 아래의 값들은 해킹 위험이 있으므로 코드상에 데이터를 넣지말고 + // 왼쪽 위에 메뉴바에서 망치 옆에 프로젝트를 눌러 edit configurations를 누르고 + // environments variables를 눌러 값을 입력해 준다. + private static String dbHost = env.get("DB_HOST"); // DB 호스트 번호(AWS 주소) 가져옴 + private static String dbUser = env.get("DB_USER"); // DB 호스트 이름 가져옴 + private static String dbPassword = env.get("DB_PASSWORD"); // DB 비밀번호 가져옴 + + + public void add() throws ClassNotFoundException { + + try{ + Class.forName("com.mysql.cj.jdbc.Driver"); // 만약 DB드라이버가 2개 이상일때 어떤 DB에 데이터를 삽입할 것인지 구분하기 위해 사용함 + // 지금은 mysql 1개만 사용하기 때문에 없어도 됨 + Connection conn = DriverManager.getConnection(dbHost,dbUser,dbPassword); // db 연결(호스트,이름,비밀번호) + PreparedStatement ps = conn.prepareStatement("INSERT INTO users(id,name,password) VALUES(?,?,?)"); + ps.setString(1,"5"); // mysql 테이블로 값 insert + ps.setString(2,"hello"); + ps.setString(3,"aaaa"); + + ps.executeUpdate(); // ctrl + enter 즉, mysql에서 번개모양을 눌러 최신화 한다는 느낌 + ps.close(); + conn.close(); + System.out.println("데이터가 insert 됬습니다."); + + }catch (SQLException e){ + throw new RuntimeException(e); + } + + } + + public User select(String id) throws SQLException, ClassNotFoundException { + Class.forName("com.mysql.cj.jdbc.Driver"); // 만약 DB드라이버가 2개 이상일때 어떤 DB에 데이터를 삽입할 것인지 구분하기 위해 사용함 + // 지금은 mysql 1개만 사용하기 때문에 없어도 됨 + Connection conn = DriverManager.getConnection(dbHost,dbUser,dbPassword); // db 연결(호스트,이름,비밀번호) + PreparedStatement ps = conn.prepareStatement("SELECT id,name,password FROM users WHERE id = ?"); + ps.setString(1,id); // id는 get(String id)로 받은 id + ResultSet rs = ps.executeQuery(); // 쿼리문을 저장함 insert문과 달리 excuteQuery() 사용 + // rs에는 쿼리 실행 결과가 담겨져 있다. (select * from users where id = 1;) + rs.next(); + + // User 생성자를 통해 쿼리문에 id값을 넣어 찾은 id, name,password 값을 저장한다. + User user = new User(rs.getString("id"),rs.getString("name"),rs.getString("password")); + rs.close(); + ps.close(); + conn.close(); + return user; + } + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + UserDao userDao = new UserDao(); + // userDao.add(); + System.out.println(userDao.select("1")); + } +} diff --git a/Project/src/main/java/Date10_12/domain/Hospital.java b/Project/src/main/java/Date10_12/domain/Hospital.java new file mode 100644 index 0000000..a1f76ac --- /dev/null +++ b/Project/src/main/java/Date10_12/domain/Hospital.java @@ -0,0 +1,125 @@ +package Date10_12.domain; + +import java.util.HashMap; +import java.util.Map; + +public class Hospital { + private String id; // [0] + private String address; //주소 [1] + private String district; //구 [1]수정 + private String category; //카테고리 [2] + private String name; //병원명 [10] + private String subDivision=""; //세부분과 [10] 수정 + private int emergencyRoom; //응급 운영 현황 [6] + + + public Hospital(String id, String address, String category, int emergencyRoom, + String name){ + this.id = id; + this.address = address; + this.category = category; + this.name = name; + this.emergencyRoom = emergencyRoom; + this.setDistrict(); + this.setCategory(); + this.setSubdivision(); + } + + public String getId() { + return id.replace("\"", ""); + } + + public String getAddress() { + return address; + } + + + public void setDistrict() { + String[] address = this.address.split(" "); + this.district = address[0] + " " + address[1]; + } + + public String getDistrict() { + return district; + } + + public void setCategory() { // 맵핑 + Map categorytmap = new HashMap<>(); + categorytmap.put("A","종합병원"); + categorytmap.put("B","병원"); + categorytmap.put("C","의원"); + categorytmap.put("D","요양병원"); + categorytmap.put("E","한방병원"); + categorytmap.put("G","한의원"); + categorytmap.put("I","기타"); + categorytmap.put("M","치과병원"); + categorytmap.put("N","치과의원"); + categorytmap.put("R","보건소"); + categorytmap.put("W","기타(구급차)"); + + this.category = categorytmap.get(category); + } + + public String getCategory() { + return category; + } + + public String setEmergencyRoom() { + if(emergencyRoom == 1){ + return "운영중"; + }else + return "운영안함"; + } + + public String getEmergencyRoom() { + return setEmergencyRoom(); + } + + public String getName() { + return name; + } + + private void setSubdivision(){ + String[] subdivisionList = new String[]{ + "치과", "성형외과", "한방병원", "한의원", "영상의학과", "이비인후과", "소아청소년과", "내과", "정형외과", "외과", + "가정의학과","피부과", "안과", "소아과", "요양병원", "비뇨기과", "정신건강의학과", "산부인과", "재활의학과", + "정신과", "마취통증의학과"}; + + for(String subdivision : subdivisionList){ + if(name.contains(subdivision)){ + subDivision=subdivision; + break; + }else + this.subDivision = "없음"; + } + + } + + public String getSubDivision() { + return subDivision; + } + + public String getSqlInsertQuery(){ + String sql = String.format("INSERT INTO `likelion-db`.`seoul_hospital`\n" + + "(`id`,`address`,`district`,`category`,`emergency_room`,`name`,`subdivision`)\n" + + "VALUES\n" + + "(\"%s\",\n" + + "\"%s\",\n" + + "\"%s\",\n" + + "\"%s\",\n" + + "%d,\n" + + "\"%s\",\n" + + "\"%s\");",this.id,this.address,this.district,this.category,this.emergencyRoom,this.name,this.subDivision); + + return sql; + } + + @Override + public String toString() { + return "\"" + this.id + "\"" + "," + "\"" + this.address + "\"" + "," + "\"" + + this.district + "\"" + "," + "\"" + this.category + "\"" + "," + this.emergencyRoom + "," + "\"" + + this.name + "\"" + "," + "\""+this.subDivision+ "\""; + } + + +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_12/domain/User.java b/Project/src/main/java/Date10_12/domain/User.java new file mode 100644 index 0000000..fd95dd8 --- /dev/null +++ b/Project/src/main/java/Date10_12/domain/User.java @@ -0,0 +1,32 @@ +package Date10_12.domain; + +public class User { + private String id; + private String name; + private String password; + + public User() { + } + + public User(String id, String name, String password) { + this.id = id; + this.name = name; + this.password = password; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String toString(){ + return "id = "+this.id + " name = "+this.name+" password = "+this.password; + } +} diff --git a/Project/src/main/java/Date10_12/pasrser/HospitalParser.java b/Project/src/main/java/Date10_12/pasrser/HospitalParser.java new file mode 100644 index 0000000..69db312 --- /dev/null +++ b/Project/src/main/java/Date10_12/pasrser/HospitalParser.java @@ -0,0 +1,82 @@ +package Date10_12.pasrser; + +import Date10_12.domain.Hospital; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; + +// 클래스에서 alt+enter를 눌러 테스트를 할 수 있다. +public class HospitalParser implements Parser{ + + static String fileaddress = "C:\\Users\\qowhx\\AppData\\Roaming\\SPB_Data\\git\\Java-Study\\lion\\test.txt"; + static Map env = System.getenv(); // 아래의 값들은 해킹 위험이 있으므로 코드상에 데이터를 넣지말고 + // 왼쪽 위에 메뉴바에서 망치 옆에 프로젝트를 눌러 edit configurations를 누르고 + // environments variables를 눌러 값을 입력해 준다. + static String dbHost = env.get("DB_HOST"); // DB 호스트 번호(AWS 주소) 가져옴 + static String dbUser = env.get("DB_USER"); // DB 호스트 이름 가져옴 + static String dbPassword = env.get("DB_PASSWORD"); // DB 비밀번호 가져옴 + + @Override + public Hospital parse(String str) { + str = str.replaceAll("\"",""); // "" 제거 + String[] splitted = str.split(","); + + return new Hospital(splitted[0],splitted[1],splitted[2],Integer.parseInt(splitted[6]),splitted[10]); + } + + public void CreateFile(){ // 파일 생성 + File file = new File(fileaddress); // 파일 생성 위치및 파일 이름 + try{ + System.out.println("파일 생성"); + file.createNewFile(); + }catch (IOException e){ + System.out.println("파일 생성 못함"); + throw new RuntimeException(); + } + } + + public void Filewrite(List hospitals){ // 파일 작성 + File file = new File(fileaddress); + + try{ + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + + for(Hospital hospital:hospitals){ // 참조변수로 받은 리스트만큼 반복 + writer.write(String.valueOf(hospital)+"\n"); // 참조변수로 받은 리스트의 값+"\n" 으로 파일에 작성 + } + writer.close(); + }catch (IOException e){ + e.printStackTrace(); + } + } + + public void insert(List hospitals) throws ClassNotFoundException, SQLException { // 자바 코드를 통해 바로 MYSQL에 데이터 삽입 + Class.forName("com.mysql.cj.jdbc.Driver"); // 만약 DB드라이버가 2개 이상일때 어떤 DB에 데이터를 삽입할 것인지 구분하기 위해 사용함 + // 지금은 mysql 1개만 사용하기 때문에 없어도 됨 + Connection conn = DriverManager.getConnection(dbHost,dbUser,dbPassword); // db 연결(호스트,이름,비밀번호) + PreparedStatement ps = conn.prepareStatement("INSERT INTO test(id,address,district,category,emergency_room,name,subdivision) VALUES(?,?,?,?,?,?,?)"); + + + for(int i =0; i { + T parse(String str); +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_20/Algorithm/stack.java b/Project/src/main/java/Date10_20/Algorithm/stack.java new file mode 100644 index 0000000..1f6e592 --- /dev/null +++ b/Project/src/main/java/Date10_20/Algorithm/stack.java @@ -0,0 +1,51 @@ +package Date10_20.Algorithm; + + +import java.util.EmptyStackException; + +public class stack { + private Integer[] arr; // 스택 저장하는 공간 + private int top = 0; // 현재 스택 최고점 위치 나타냄 + + public stack() { // 생성자를 통해 배열의 크기를 초기화함 + this.arr = new Integer[10000]; + } + + public stack(int size) { + this.arr = new Integer[10000]; + } + + public Integer[] getArr() { + return arr; + } + + public void push(int value) { + // 10을 넣으면 arr[0] = 10 + this.arr[top++] = value; + } + +// 예외처리 전 +// public int pop() { +// return this.arr[--this.top]; +// } + + public int pop() { + if (this.isEmpty()) { + throw new RuntimeException("스택이 비었습니다."); + } + return this.arr[--this.top]; + } + + public boolean isEmpty() { + boolean isEmpty = this.top == 0; + return isEmpty; + } + + public int peek() { + if (this.isEmpty()) { + throw new EmptyStackException(); + } + return this.arr[this.top - 1]; + } +} + diff --git a/Project/src/main/java/Date10_20/dao/Abstract/AWSUserDaoImpl.java b/Project/src/main/java/Date10_20/dao/Abstract/AWSUserDaoImpl.java new file mode 100644 index 0000000..f881ebb --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Abstract/AWSUserDaoImpl.java @@ -0,0 +1,26 @@ +package Date10_20.dao.Abstract; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Map; + +// 추상화 클래스 상속 받음 +// AWS 저장소에 연결함 (2번째 방식) +public class AWSUserDaoImpl extends UserDaoAbstract{ + @Override + public Connection makeConnection() throws SQLException { + Map env = System.getenv(); // 아래의 값들은 해킹 위험이 있으므로 코드상에 데이터를 넣지말고 + // 왼쪽 위에 메뉴바에서 망치 옆에 프로젝트를 눌러 edit configurations를 누르고 + // environments variables를 눌러 값을 입력해 준다. + String dbHost = env.get("DB_HOST"); // DB 호스트 번호(AWS 주소) 가져옴 + String dbUser = env.get("DB_USER"); // DB 호스트 이름 가져옴 + String dbPassword = env.get("DB_PASSWORD"); // DB 비밀번호 가져옴 + + Connection conn = DriverManager.getConnection(dbHost,dbUser,dbPassword); + + // 외부에서 주소와 호스트정보 비밀번호 입력 + + return conn; + } +} diff --git a/Project/src/main/java/Date10_20/dao/Abstract/LocalUserDaoImpl.java b/Project/src/main/java/Date10_20/dao/Abstract/LocalUserDaoImpl.java new file mode 100644 index 0000000..c2af8eb --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Abstract/LocalUserDaoImpl.java @@ -0,0 +1,24 @@ +package Date10_20.dao.Abstract; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Map; + +// 추상화 상속받음 +// 로컬 저장소 연결 (2번째 방식) +public class LocalUserDaoImpl extends UserDaoAbstract{ + @Override + public Connection makeConnection() throws SQLException { + Map env = System.getenv(); // 아래의 값들은 해킹 위험이 있으므로 코드상에 데이터를 넣지말고 + // 왼쪽 위에 메뉴바에서 망치 옆에 프로젝트를 눌러 edit configurations를 누르고 + // environments variables를 눌러 값을 입력해 준다. + + Connection conn = DriverManager.getConnection( + "jdbc:mysql://localhost:3306" + ,"root","12345678"); + // Local 저장소는 데이터를 코드상에 입력해도 해커가 털어가기 힘들다. + + return conn; + } +} diff --git a/Project/src/main/java/Date10_20/dao/Abstract/UserDaoAbstract.java b/Project/src/main/java/Date10_20/dao/Abstract/UserDaoAbstract.java new file mode 100644 index 0000000..918c200 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Abstract/UserDaoAbstract.java @@ -0,0 +1,69 @@ +package Date10_20.dao.Abstract; + +import Date10_20.domain.User; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +// 추상화를 통해 여러 DB의 값들을 따로 호출하여 사용하는 방법 (2번째 방식) + + +public abstract class UserDaoAbstract { + + public abstract Connection makeConnection() throws SQLException; + // DB를 여러개 동시에 사용하는 경우 각 DB에 연결시켜야 하므로 추상화 클래스를 상속받아 + // 원하는 DB로 연결시키는 방식에 사용 + + public void add(User user) throws ClassNotFoundException { + + try{ + // db 연결(호스트,이름,비밀번호) + Connection conn = makeConnection(); // 설정들을 모아둔 메서드 호출 + + PreparedStatement ps = conn.prepareStatement("INSERT INTO users(id,name,password) VALUES(?,?,?)"); + ps.setString(1,user.getId()); // mysql 테이블로 값 insert + ps.setString(2,user.getName()); + ps.setString(3,user.getPassword()); + + ps.executeUpdate(); // ctrl + enter 즉, mysql에서 번개모양을 눌러 최신화 한다는 느낌 + ps.close(); + conn.close(); + System.out.println("데이터가 insert 됬습니다."); + + }catch (SQLException e){ + throw new RuntimeException(e); + } + + } + + public User select(String id) throws SQLException, ClassNotFoundException { + + try { + Connection conn = makeConnection(); + PreparedStatement ps = conn.prepareStatement("SELECT id,name,password FROM users WHERE id = ?"); + ps.setString(1, id); // id는 get(String id)로 받은 id + ResultSet rs = ps.executeQuery(); // 쿼리문을 저장함 insert문과 달리 excuteQuery() 사용 + // rs에는 쿼리 실행 결과가 담겨져 있다. (select * from users where id = 1;) + rs.next(); + + // User 생성자를 통해 쿼리문에 id값을 넣어 찾은 id, name,password 값을 저장한다. + User user = new User(rs.getString("id"), rs.getString("name"), rs.getString("password")); + rs.close(); + ps.close(); + conn.close(); + return user; + }catch (SQLException e){ + throw new RuntimeException(e); + } + } + + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + AWSUserDaoImpl userDao = new AWSUserDaoImpl(); + userDao.add(new User("7","Ruru","1234qwer")); // user로 값을 받아 DTO에 저장한 후 mysql로 데이터 보냄 + System.out.println(userDao.select("1")); + } + +} diff --git a/Project/src/main/java/Date10_20/dao/Connection/UserDao.java b/Project/src/main/java/Date10_20/dao/Connection/UserDao.java new file mode 100644 index 0000000..ceacfa7 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Connection/UserDao.java @@ -0,0 +1,74 @@ +package Date10_20.dao.Connection; + +import Date10_20.domain.User; + +import java.sql.*; +import java.util.Map; + +// 중복코드만 따로 빼내서 작성한 코드 (첫번째 방식) +public class UserDao { + + private Connection makeConnection() throws ClassNotFoundException, SQLException { + Map env = System.getenv(); // 아래의 값들은 해킹 위험이 있으므로 코드상에 데이터를 넣지말고 + // 왼쪽 위에 메뉴바에서 망치 옆에 프로젝트를 눌러 edit configurations를 누르고 + // environments variables를 눌러 값을 입력해 준다. + String dbHost = env.get("DB_HOST"); // DB 호스트 번호(AWS 주소) 가져옴 + String dbUser = env.get("DB_USER"); // DB 호스트 이름 가져옴 + String dbPassword = env.get("DB_PASSWORD"); // DB 비밀번호 가져옴 + + Class.forName("com.mysql.cj.jdbc.Driver"); // 만약 DB드라이버가 2개 이상일때 어떤 DB에 데이터를 삽입할 것인지 구분하기 위해 사용함 + // 지금은 mysql 1개만 사용하기 때문에 없어도 됨 + Connection conn = DriverManager.getConnection(dbHost,dbUser,dbPassword); + + return conn; + } + + public void add(User user) throws ClassNotFoundException { + + try{ + // db 연결(호스트,이름,비밀번호) + Connection conn = makeConnection(); // 설정들을 모아둔 메서드 호출 + + PreparedStatement ps = conn.prepareStatement("INSERT INTO users(id,name,password) VALUES(?,?,?)"); + ps.setString(1,user.getId()); // mysql 테이블로 값 insert + ps.setString(2,user.getName()); + ps.setString(3,user.getPassword()); + + ps.executeUpdate(); // ctrl + enter 즉, mysql에서 번개모양을 눌러 최신화 한다는 느낌 + ps.close(); + conn.close(); + System.out.println("데이터가 insert 됬습니다."); + + }catch (SQLException e){ + throw new RuntimeException(e); + } + + } + + public User select(String id) throws SQLException, ClassNotFoundException { + + try { + Connection conn = makeConnection(); + PreparedStatement ps = conn.prepareStatement("SELECT id,name,password FROM users WHERE id = ?"); + ps.setString(1, id); // id는 get(String id)로 받은 id + ResultSet rs = ps.executeQuery(); // 쿼리문을 저장함 insert문과 달리 excuteQuery() 사용 + // rs에는 쿼리 실행 결과가 담겨져 있다. (select * from users where id = 1;) + rs.next(); + + // User 생성자를 통해 쿼리문에 id값을 넣어 찾은 id, name,password 값을 저장한다. + User user = new User(rs.getString("id"), rs.getString("name"), rs.getString("password")); + rs.close(); + ps.close(); + conn.close(); + return user; + }catch (SQLException e){ + throw new RuntimeException(e); + } + } + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + UserDao userDao = new UserDao(); + userDao.add(new User("7","Ruru","1234qwer")); // user로 값을 받아 DTO에 저장한 후 mysql로 데이터 보냄 + System.out.println(userDao.select("1")); + } +} diff --git a/Project/src/main/java/Date10_20/dao/Factory/AWSConnectionMaker.java b/Project/src/main/java/Date10_20/dao/Factory/AWSConnectionMaker.java new file mode 100644 index 0000000..9149314 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Factory/AWSConnectionMaker.java @@ -0,0 +1,23 @@ +package Date10_20.dao.Factory; + +// AWS DB 연결 +// 2번째 방식을 클래스로 따로 빼내어 사용하는 방식 (3번째 방법) +// interface 상속 +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Map; + +public class AWSConnectionMaker implements ConnectionMaker{ + @Override + public Connection makeConnection() throws SQLException, ClassNotFoundException { + Map env = System.getenv(); // 환경변수를 사용하여 + String dbHost = env.get("DB_HOST"); + String dbUser = env.get("DB_USER"); + String dbPassword = env.get("DB_PASSWORD"); + + Class.forName("com.mysql.cj.jdbc.Driver"); + Connection conn = DriverManager.getConnection(dbHost, dbUser, dbPassword); + return conn; + } +} diff --git a/Project/src/main/java/Date10_20/dao/Factory/ConnectionMaker.java b/Project/src/main/java/Date10_20/dao/Factory/ConnectionMaker.java new file mode 100644 index 0000000..7424cdf --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Factory/ConnectionMaker.java @@ -0,0 +1,8 @@ +package Date10_20.dao.Factory; + +import java.sql.Connection; +import java.sql.SQLException; + +public interface ConnectionMaker { // makeConnection을 각 DB에 맞게 사용할 수 있도록 불러오기 위한 interface + Connection makeConnection() throws SQLException, ClassNotFoundException; +} diff --git a/Project/src/main/java/Date10_20/dao/Factory/LocalConnectionMaker.java b/Project/src/main/java/Date10_20/dao/Factory/LocalConnectionMaker.java new file mode 100644 index 0000000..edeab66 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Factory/LocalConnectionMaker.java @@ -0,0 +1,16 @@ +package Date10_20.dao.Factory; + + +// local DB 연결 +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class LocalConnectionMaker implements ConnectionMaker{ + @Override + public Connection makeConnection() throws SQLException { + Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/likelion-db","root","password"); + + return conn; + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_20/dao/Factory/UserDao.java b/Project/src/main/java/Date10_20/dao/Factory/UserDao.java new file mode 100644 index 0000000..e15acc9 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Factory/UserDao.java @@ -0,0 +1,160 @@ +package Date10_20.dao.Factory; + +import Date10_20.domain.User; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +// 중복코드만 따로 빼내서 작성한 코드 (3번째 방식) +public class UserDao { + + private ConnectionMaker connectionMaker; // interface의 makeConnection()를 가져옴 + public UserDao(){ // 생성자를 통해 AWS DB의 makeConnection()을 오버라이딩하여 사용 + this.connectionMaker = new AWSConnectionMaker(); + } + public UserDao(ConnectionMaker connectionMaker){ + this.connectionMaker = connectionMaker; + } + + + public void deleteAll() throws SQLException, ClassNotFoundException { // DB 모든값 삭제 + Connection conn = null; + PreparedStatement ps = null; + + try { // 예외처리 + conn = connectionMaker.makeConnection(); + ps = conn.prepareStatement("delete from users "); + ps.executeUpdate(); + } catch (SQLException e) { + throw new RuntimeException(e); + }finally { // error 발생해도 실행함 + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } + + public int getCount() throws SQLException, ClassNotFoundException { // user테이블의 레코드 개수를 구하기 + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try { + conn = connectionMaker.makeConnection(); + ps = conn.prepareStatement("select count(*) from users "); + rs = ps.executeQuery(); + rs.next(); + return rs.getInt(1); + + } catch (SQLException e) { + throw new RuntimeException(e); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } finally { + if(rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } + + public void add(User user) throws ClassNotFoundException, SQLException { + // db 연결(호스트,이름,비밀번호) + Connection conn = null; // 설정들을 모아둔 메서드 호출 + PreparedStatement ps = null; + try { + conn = connectionMaker.makeConnection(); + + ps = conn.prepareStatement("INSERT INTO users(id,name,password) VALUES(?,?,?)"); + ps.setString(1,user.getId()); // mysql 테이블로 값 insert + ps.setString(2,user.getName()); + ps.setString(3,user.getPassword()); + ps.executeUpdate(); // ctrl + enter 즉, mysql에서 번개모양을 눌러 최신화 한다는 느낌 + } catch (SQLException e) { + throw new RuntimeException(e); + }finally { + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + System.out.println("데이터가 insert 됬습니다."); + } + } + + public User select(String id) throws SQLException, ClassNotFoundException { + + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; // 쿼리문을 저장함 insert문과 달리 excuteQuery() 사용 + User user = null; + try { + conn = connectionMaker.makeConnection(); + ps = conn.prepareStatement("SELECT id,name,password FROM users WHERE id = ?"); + ps.setString(1, id); // id는 get(String id)로 받은 id + rs = ps.executeQuery(); + // rs에는 쿼리 실행 결과가 담겨져 있다. (select * from users where id = 1;) + rs.next(); + // User 생성자를 통해 쿼리문에 id값을 넣어 찾은 id, name,password 값을 저장한다. + return new User(rs.getString("id"), rs.getString("name"), rs.getString("password")); + } + catch (SQLException e) { + throw new RuntimeException(e); + } + finally { + if(rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_20/dao/Factory/UserDaoFactory.java b/Project/src/main/java/Date10_20/dao/Factory/UserDaoFactory.java new file mode 100644 index 0000000..b018620 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Factory/UserDaoFactory.java @@ -0,0 +1,26 @@ +package Date10_20.dao.Factory; + + +// 인터페이스로 받은 것을 어떤것을 UserDaoInterface로 넘겨줄것인지 설정 +// 즉, 인터페이스로 DB별 연결 설정을 나눠놨는데 여기서 메서드별로 다시 DB별로 나누어 +// UserDaoInterface로 해당 DB 연결 설정 값을 보냄 +// (4번째 방식) +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class UserDaoFactory { + + @Bean + public UserDao awsUserDao(){ + AWSConnectionMaker awsConnectionMaker = new AWSConnectionMaker(); + UserDao userDao = new UserDao(awsConnectionMaker); + return userDao; + } + + @Bean + public UserDao localUserDao(){ + UserDao userDao = new UserDao(new LocalConnectionMaker()); + return userDao; + } +} diff --git a/Project/src/main/java/Date10_20/dao/Interface/AWSConnectionMaker.java b/Project/src/main/java/Date10_20/dao/Interface/AWSConnectionMaker.java new file mode 100644 index 0000000..071b794 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Interface/AWSConnectionMaker.java @@ -0,0 +1,23 @@ +package Date10_20.dao.Interface; + +// AWS DB 연결 +// 2번째 방식을 클래스로 따로 빼내어 사용하는 방식 (3번째 방법) +// interface 상속 +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Map; + +public class AWSConnectionMaker implements ConnectionMaker { + @Override + public Connection makeConnection() throws SQLException, ClassNotFoundException { + Map env = System.getenv(); // 환경변수를 사용하여 + String dbHost = env.get("DB_HOST"); + String dbUser = env.get("DB_USER"); + String dbPassword = env.get("DB_PASSWORD"); + + Class.forName("com.mysql.cj.jdbc.Driver"); + Connection conn = DriverManager.getConnection(dbHost, dbUser, dbPassword); + return conn; + } +} diff --git a/Project/src/main/java/Date10_20/dao/Interface/ConnectionMaker.java b/Project/src/main/java/Date10_20/dao/Interface/ConnectionMaker.java new file mode 100644 index 0000000..764d309 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Interface/ConnectionMaker.java @@ -0,0 +1,8 @@ +package Date10_20.dao.Interface; + +import java.sql.Connection; +import java.sql.SQLException; + +public interface ConnectionMaker { // makeConnection을 각 DB에 맞게 사용할 수 있도록 불러오기 위한 interface + Connection makeConnection() throws SQLException, ClassNotFoundException; +} diff --git a/Project/src/main/java/Date10_20/dao/Interface/LocalConnectionMaker.java b/Project/src/main/java/Date10_20/dao/Interface/LocalConnectionMaker.java new file mode 100644 index 0000000..33efe51 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Interface/LocalConnectionMaker.java @@ -0,0 +1,16 @@ +package Date10_20.dao.Interface; + + +// local DB 연결 +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +public class LocalConnectionMaker implements ConnectionMaker { + @Override + public Connection makeConnection() throws SQLException { + Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/likelion-db","root","password"); + + return conn; + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_20/dao/Interface/UserDaoInterface.java b/Project/src/main/java/Date10_20/dao/Interface/UserDaoInterface.java new file mode 100644 index 0000000..0d2281a --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/Interface/UserDaoInterface.java @@ -0,0 +1,69 @@ +package Date10_20.dao.Interface; + +import Date10_20.domain.User; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +// 중복코드만 따로 빼내서 작성한 코드 (3번째 방식) +public class UserDaoInterface { + + private ConnectionMaker connectionMaker; // interface의 makeConnection()를 가져옴 + public UserDaoInterface(){ // 생성자를 통해 AWS DB의 makeConnection()을 오버라이딩하여 사용 + this.connectionMaker = new AWSConnectionMaker(); + } // 생성자 기본값을 AWS주소로 설정 + public UserDaoInterface(ConnectionMaker connectionMaker){ + this.connectionMaker = connectionMaker; + } + + public void add(User user) throws ClassNotFoundException { + + try{ + // db 연결(호스트,이름,비밀번호) + Connection conn = connectionMaker.makeConnection(); // 설정들을 모아둔 메서드 호출 + + PreparedStatement ps = conn.prepareStatement("INSERT INTO users(id,name,password) VALUES(?,?,?)"); + ps.setString(1,user.getId()); // mysql 테이블로 값 insert + ps.setString(2,user.getName()); + ps.setString(3,user.getPassword()); + + ps.executeUpdate(); // ctrl + enter 즉, mysql에서 번개모양을 눌러 최신화 한다는 느낌 + ps.close(); + conn.close(); + System.out.println("데이터가 insert 됬습니다."); + + }catch (SQLException e){ + throw new RuntimeException(e); + } + + } + + public User select(String id) throws SQLException, ClassNotFoundException { + + try { + Connection conn = connectionMaker.makeConnection(); + PreparedStatement ps = conn.prepareStatement("SELECT id,name,password FROM users WHERE id = ?"); + ps.setString(1, id); // id는 get(String id)로 받은 id + ResultSet rs = ps.executeQuery(); // 쿼리문을 저장함 insert문과 달리 excuteQuery() 사용 + // rs에는 쿼리 실행 결과가 담겨져 있다. (select * from users where id = 1;) + rs.next(); + + // User 생성자를 통해 쿼리문에 id값을 넣어 찾은 id, name,password 값을 저장한다. + User user = new User(rs.getString("id"), rs.getString("name"), rs.getString("password")); + rs.close(); + ps.close(); + conn.close(); + return user; + }catch (SQLException e){ + throw new RuntimeException(e); + } + } + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + UserDaoInterface userDao = new UserDaoInterface(); + userDao.add(new User("7","Ruru","1234qwer")); // user로 값을 받아 DTO에 저장한 후 mysql로 데이터 보냄 + System.out.println(userDao.select("1")); + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_20/dao/UserDaoConnectionMaker.java b/Project/src/main/java/Date10_20/dao/UserDaoConnectionMaker.java new file mode 100644 index 0000000..fcc4ec2 --- /dev/null +++ b/Project/src/main/java/Date10_20/dao/UserDaoConnectionMaker.java @@ -0,0 +1,67 @@ +package Date10_20.dao; + +import Date10_20.dao.Factory.AWSConnectionMaker; +import Date10_20.domain.User; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +// 2번째 방식을 클래스로 따로 빼내어 사용하는 방식 (3번째 방법) +public class UserDaoConnectionMaker { + + AWSConnectionMaker awsConnectionMaker; + + public UserDaoConnectionMaker(AWSConnectionMaker awsConnectionMaker) { + this.awsConnectionMaker = awsConnectionMaker; + } + + public void add(User user) throws ClassNotFoundException { + + try{ + // db 연결(호스트,이름,비밀번호) + Connection conn = awsConnectionMaker.makeConnection(); // 설정들을 모아둔 메서드 호출 + + PreparedStatement ps = conn.prepareStatement("INSERT INTO users(id,name,password) VALUES(?,?,?)"); + ps.setString(1,user.getId()); // mysql 테이블로 값 insert + ps.setString(2,user.getName()); + ps.setString(3,user.getPassword()); + + ps.executeUpdate(); // ctrl + enter 즉, mysql에서 번개모양을 눌러 최신화 한다는 느낌 + ps.close(); + conn.close(); + System.out.println("데이터가 insert 됬습니다."); + + }catch (SQLException e){ + throw new RuntimeException(e); + } + + } + + public User select(String id) throws SQLException, ClassNotFoundException { + + try { + Connection conn = awsConnectionMaker.makeConnection(); + PreparedStatement ps = conn.prepareStatement("SELECT id,name,password FROM users WHERE id = ?"); + ps.setString(1, id); // id는 get(String id)로 받은 id + ResultSet rs = ps.executeQuery(); // 쿼리문을 저장함 insert문과 달리 excuteQuery() 사용 + // rs에는 쿼리 실행 결과가 담겨져 있다. (select * from users where id = 1;) + rs.next(); + + // User 생성자를 통해 쿼리문에 id값을 넣어 찾은 id, name,password 값을 저장한다. + User user = new User(rs.getString("id"), rs.getString("name"), rs.getString("password")); + rs.close(); + ps.close(); + conn.close(); + return user; + }catch (SQLException e){ + throw new RuntimeException(e); + } + } + + public static void main(String[] args) throws ClassNotFoundException, SQLException { + UserDaoConnectionMaker userDao = new UserDaoConnectionMaker(new AWSConnectionMaker()); + userDao.add(new User("7","Ruru","1234qwer")); // user로 값을 받아 DTO에 저장한 후 mysql로 데이터 보냄 + System.out.println(userDao.select("1")); + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_20/domain/User.java b/Project/src/main/java/Date10_20/domain/User.java new file mode 100644 index 0000000..81a462a --- /dev/null +++ b/Project/src/main/java/Date10_20/domain/User.java @@ -0,0 +1,32 @@ +package Date10_20.domain; + +public class User { + private String id; + private String name; + private String password; + + public User() { + } + + public User(String id, String name, String password) { + this.id = id; + this.name = name; + this.password = password; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String toString(){ + return "id = "+this.id + " name = "+this.name+" password = "+this.password; + } +} diff --git a/Project/src/main/java/Date10_21/Algorithm/StackBracket.java b/Project/src/main/java/Date10_21/Algorithm/StackBracket.java new file mode 100644 index 0000000..27799cf --- /dev/null +++ b/Project/src/main/java/Date10_21/Algorithm/StackBracket.java @@ -0,0 +1,22 @@ +package Date10_21.Algorithm; + +import java.util.Stack; + +public class StackBracket { + boolean answer(String s){ + Stack stack = new Stack<>(); + + for(int i =0; i= 0){ // ()를 문자열에서 index 값을 찾음 + // 만약 인덱스 값이 0보다 크면 + s = s.replace("()",""); // ()를 ""으로 바꿈 + // 예시. (()) 일때 () = index 1이므로 while문 동작 + // "" 자리 바꿔서 () 출력후 다시 반복 + } + + return s.length()==0; // s 문자열의 길이가 0이면 ()가 짝수 이므로 True 반환 + } +} diff --git a/Project/src/main/java/Date10_21/Algorithm/bracket2.java b/Project/src/main/java/Date10_21/Algorithm/bracket2.java new file mode 100644 index 0000000..08c73a2 --- /dev/null +++ b/Project/src/main/java/Date10_21/Algorithm/bracket2.java @@ -0,0 +1,13 @@ +package Date10_21.Algorithm; + +// split, join 사용하여 풀기 + +public class bracket2{ + public boolean result2(String s){ + while(s.indexOf("()")>= 0){ + String[] splitted = s.split("\\(\\)"); + s = String.join("",splitted); // join 배열을 문자열로 변경 + } + return s.length()==0; + } +} diff --git a/Project/src/main/java/Date10_21/Factory/AWSConnectionMaker.java b/Project/src/main/java/Date10_21/Factory/AWSConnectionMaker.java new file mode 100644 index 0000000..833c3b2 --- /dev/null +++ b/Project/src/main/java/Date10_21/Factory/AWSConnectionMaker.java @@ -0,0 +1,24 @@ +package Date10_21.Factory; + +// AWS DB 연결 +// 2번째 방식을 클래스로 따로 빼내어 사용하는 방식 (3번째 방법) +// interface 상속 + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.Map; + +public class AWSConnectionMaker implements ConnectionMaker { + @Override + public Connection makeConnection() throws SQLException, ClassNotFoundException { + Map env = System.getenv(); // 환경변수를 사용하여 + String dbHost = env.get("DB_HOST"); + String dbUser = env.get("DB_USER"); + String dbPassword = env.get("DB_PASSWORD"); + + Class.forName("com.mysql.cj.jdbc.Driver"); + Connection conn = DriverManager.getConnection(dbHost, dbUser, dbPassword); + return conn; + } +} diff --git a/Project/src/main/java/Date10_21/Factory/AddStrategy.java b/Project/src/main/java/Date10_21/Factory/AddStrategy.java new file mode 100644 index 0000000..8bff2fc --- /dev/null +++ b/Project/src/main/java/Date10_21/Factory/AddStrategy.java @@ -0,0 +1,26 @@ +package Date10_21.Factory; + +import Date10_21.domain.User; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class AddStrategy implements StatementStrategy{ + + private User user; + + public AddStrategy(User user){ + this.user =user; + } + + @Override + public PreparedStatement makepreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement("INSERT INTO users(id,name,password) VALUES(?,?,?)"); + ps.setString(1,user.getId()); // mysql 테이블로 값 insert + ps.setString(2,user.getName()); + ps.setString(3,user.getPassword()); + + return ps; + } +} diff --git a/Project/src/main/java/Date10_21/Factory/ConnectionMaker.java b/Project/src/main/java/Date10_21/Factory/ConnectionMaker.java new file mode 100644 index 0000000..dd28402 --- /dev/null +++ b/Project/src/main/java/Date10_21/Factory/ConnectionMaker.java @@ -0,0 +1,8 @@ +package Date10_21.Factory; + +import java.sql.Connection; +import java.sql.SQLException; + +public interface ConnectionMaker { // makeConnection을 각 DB에 맞게 사용할 수 있도록 불러오기 위한 interface + Connection makeConnection() throws SQLException, ClassNotFoundException; +} diff --git a/Project/src/main/java/Date10_21/Factory/DeleteAllStrategy.java b/Project/src/main/java/Date10_21/Factory/DeleteAllStrategy.java new file mode 100644 index 0000000..be2dca1 --- /dev/null +++ b/Project/src/main/java/Date10_21/Factory/DeleteAllStrategy.java @@ -0,0 +1,17 @@ +package Date10_21.Factory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + + +// Delete 쿼리문 클래스 +public class DeleteAllStrategy implements StatementStrategy{ + + @Override + public PreparedStatement makepreparedStatement(Connection connection) throws SQLException { + return connection.prepareStatement("delete from users"); + } +} + + diff --git a/Project/src/main/java/Date10_21/Factory/LocalConnectionMaker.java b/Project/src/main/java/Date10_21/Factory/LocalConnectionMaker.java new file mode 100644 index 0000000..8083788 --- /dev/null +++ b/Project/src/main/java/Date10_21/Factory/LocalConnectionMaker.java @@ -0,0 +1,18 @@ +package Date10_21.Factory; + + +// local DB 연결 + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + + +public class LocalConnectionMaker implements ConnectionMaker { + @Override + public Connection makeConnection() throws SQLException { + Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/likelion-db","root","password"); + + return conn; + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_21/Factory/StatementStrategy.java b/Project/src/main/java/Date10_21/Factory/StatementStrategy.java new file mode 100644 index 0000000..a6562cf --- /dev/null +++ b/Project/src/main/java/Date10_21/Factory/StatementStrategy.java @@ -0,0 +1,11 @@ +package Date10_21.Factory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +// 쿼리문을 DAO 클래스에 작성하지 않고 따로 interface를 통해 각자 별도 클래스 생성함 +public interface StatementStrategy { + PreparedStatement makepreparedStatement(Connection connection) throws SQLException; + +} diff --git a/Project/src/main/java/Date10_21/Factory/UserDao.java b/Project/src/main/java/Date10_21/Factory/UserDao.java new file mode 100644 index 0000000..dc8a3c5 --- /dev/null +++ b/Project/src/main/java/Date10_21/Factory/UserDao.java @@ -0,0 +1,140 @@ +package Date10_21.Factory; + +import Date10_21.domain.User; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +// 중복코드만 따로 빼내서 작성한 코드 (3번째 방식) +public class UserDao { + + private ConnectionMaker connectionMaker; // interface의 makeConnection()를 가져옴 + public UserDao(){ // 생성자를 통해 AWS DB의 makeConnection()을 오버라이딩하여 사용 + this.connectionMaker = new AWSConnectionMaker(); + } + public UserDao(ConnectionMaker connectionMaker){ + this.connectionMaker = connectionMaker; + } + + // add,delete등 sql문을 사용하는 메서드들은 쿼리문(insert, delete,select 등)만 다르지 구조는 모두 같다 + // 따라서 이러한 중복되는 구조들을 하나의 메서드로 정의한 후 호출하여 사용함 + public void jdbcContextWithStatementStatementstrategy(StatementStrategy st){ + Connection conn = null; + PreparedStatement ps = null; + + try { // 예외처리 + conn = connectionMaker.makeConnection(); + ps = new DeleteAllStrategy().makepreparedStatement(conn); + ps.executeUpdate(); + } catch (SQLException | ClassNotFoundException e) { + throw new RuntimeException(e); + }finally { // error 발생해도 실행함 + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } + + public void deleteAll() throws SQLException, ClassNotFoundException { // DB 모든값 삭제 + jdbcContextWithStatementStatementstrategy(new DeleteAllStrategy()); + } + + public int getCount() throws SQLException, ClassNotFoundException { // user테이블의 레코드 개수를 구하기 + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try { + conn = connectionMaker.makeConnection(); + ps = conn.prepareStatement("select count(*) from users "); + rs = ps.executeQuery(); + rs.next(); + return rs.getInt(1); + + } catch (SQLException e) { + throw new RuntimeException(e); + } catch (ClassNotFoundException e) { + throw new RuntimeException(e); + } finally { + if(rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } + + public void add(User user) throws ClassNotFoundException, SQLException { + AddStrategy addStrategy = new AddStrategy(user); // User DTO에 저장되어 있는 값 가져옴 + jdbcContextWithStatementStatementstrategy(addStrategy); // add 쿼리문과 추가할 값 가져와서 대입 + + System.out.println("데이터가 insert 됬습니다"); + } + + public User select(String id) throws SQLException, ClassNotFoundException { + + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; // 쿼리문을 저장함 insert문과 달리 excuteQuery() 사용 + User user = null; + try { + conn = connectionMaker.makeConnection(); + ps = conn.prepareStatement("SELECT id,name,password FROM users WHERE id = ?"); + ps.setString(1, id); // id는 get(String id)로 받은 id + rs = ps.executeQuery(); + // rs에는 쿼리 실행 결과가 담겨져 있다. (select * from users where id = 1;) + rs.next(); + // User 생성자를 통해 쿼리문에 id값을 넣어 찾은 id, name,password 값을 저장한다. + return new User(rs.getString("id"), rs.getString("name"), rs.getString("password")); + } + catch (SQLException e) { + throw new RuntimeException(e); + } + finally { + if(rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_21/Factory/UserDaoFactory.java b/Project/src/main/java/Date10_21/Factory/UserDaoFactory.java new file mode 100644 index 0000000..65a0358 --- /dev/null +++ b/Project/src/main/java/Date10_21/Factory/UserDaoFactory.java @@ -0,0 +1,26 @@ +package Date10_21.Factory; + + +// 인터페이스로 받은 것을 어떤것을 UserDaoInterface로 넘겨줄것인지 설정 +// 즉, 인터페이스로 DB별 연결 설정을 나눠놨는데 여기서 메서드별로 다시 DB별로 나누어 +// UserDaoInterface로 해당 DB 연결 설정 값을 보냄 +// (4번째 방식) +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +@Configuration +public class UserDaoFactory { + + @Bean + public UserDao awsUserDao(){ + AWSConnectionMaker awsConnectionMaker = new AWSConnectionMaker(); + UserDao userDao = new UserDao(awsConnectionMaker); + return userDao; + } + + @Bean + public UserDao localUserDao(){ + UserDao userDao = new UserDao(new LocalConnectionMaker()); + return userDao; + } +} diff --git a/Project/src/main/java/Date10_21/domain/User.java b/Project/src/main/java/Date10_21/domain/User.java new file mode 100644 index 0000000..36303d4 --- /dev/null +++ b/Project/src/main/java/Date10_21/domain/User.java @@ -0,0 +1,32 @@ +package Date10_21.domain; + +public class User { + private String id; + private String name; + private String password; + + public User() { + } + + public User(String id, String name, String password) { + this.id = id; + this.name = name; + this.password = password; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String toString(){ + return "id = "+this.id + " name = "+this.name+" password = "+this.password; + } +} diff --git a/Project/src/main/java/Date10_24/Algorithm/Solution.java b/Project/src/main/java/Date10_24/Algorithm/Solution.java new file mode 100644 index 0000000..127001b --- /dev/null +++ b/Project/src/main/java/Date10_24/Algorithm/Solution.java @@ -0,0 +1,31 @@ +package Date10_24.Algorithm; + +import java.util.Arrays; + +/* 프로그래머스 K번째 수 구하기 +질문 : array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면 + array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다. + 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다. + 2에서 나온 배열의 3번째 숫자는 5입니다. + i는 최소 1이여야함 + */ +public class Solution { + public int[] solution(int[] arr,int[][]commands){ + int[] answer = new int[commands.length]; + int idx = 0; + for(int[] command : commands){ // ex) [2,5,3] 들어감 + int[] slicedArr = Arrays.copyOfRange(arr,command[0]-1,command[1]); // 배열을 자른다 2-1,5 => 1~4까지 자름 [5,2,6,3] + Arrays.sort(slicedArr); // 배열을 정렬한다. [2,3,5,6] + answer[idx++] = slicedArr[command[2]-1]; //3-1 = 2번째 자리 수 저장함, 5 저장 + } + return answer; + } + + public static void main(String[] args) { + Solution s = new Solution(); + int[] arr = {1,5,2,6,3,7,4}; + int[][] commands = {{2,5,3},{4,4,1},{1,7,3}}; + + System.out.println(Arrays.toString(s.solution(arr,commands))); + } +} diff --git a/Project/src/main/java/Date10_24/Algorithm/Solution2.java b/Project/src/main/java/Date10_24/Algorithm/Solution2.java new file mode 100644 index 0000000..d463fe4 --- /dev/null +++ b/Project/src/main/java/Date10_24/Algorithm/Solution2.java @@ -0,0 +1,21 @@ +package Date10_24.Algorithm; + +import java.util.PriorityQueue; + +// 우선순위 큐 사용 +public class Solution2 { + public int[] solution2(int[] arr, int[][] commands) { + int[] answer = new int[commands.length]; + for (int i = 0; i < commands.length; i++) { + PriorityQueue pq = new PriorityQueue<>(); + + for (int j = commands[i][0] - 1; j < commands[i][1]; j++) { + pq.add(arr[j]); // 우선순위 큐에 from, to까지 넣기 + } + for (int j = 0; j < commands[i][2]; j++) { + answer[i] = pq.poll(); //stack의 pop과 + } + } + return answer; + } +} diff --git a/Project/src/main/java/Date10_24/Factory/AddStrategy.java b/Project/src/main/java/Date10_24/Factory/AddStrategy.java new file mode 100644 index 0000000..b62baf6 --- /dev/null +++ b/Project/src/main/java/Date10_24/Factory/AddStrategy.java @@ -0,0 +1,26 @@ +package Date10_24.Factory; + +import Date10_24.domain.User; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +public class AddStrategy implements StatementStrategy { + + private User user; + + public AddStrategy(User user){ + this.user =user; + } + + @Override + public PreparedStatement makepreparedStatement(Connection connection) throws SQLException { + PreparedStatement ps = connection.prepareStatement("INSERT INTO users(id,name,password) VALUES(?,?,?)"); + ps.setString(1,user.getId()); // mysql 테이블로 값 insert + ps.setString(2,user.getName()); + ps.setString(3,user.getPassword()); + + return ps; + } +} diff --git a/Project/src/main/java/Date10_24/Factory/DeleteAllStrategy.java b/Project/src/main/java/Date10_24/Factory/DeleteAllStrategy.java new file mode 100644 index 0000000..1613e22 --- /dev/null +++ b/Project/src/main/java/Date10_24/Factory/DeleteAllStrategy.java @@ -0,0 +1,17 @@ +package Date10_24.Factory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + + +// Delete 쿼리문 클래스 +public class DeleteAllStrategy implements StatementStrategy { + + @Override + public PreparedStatement makepreparedStatement(Connection connection) throws SQLException { + return connection.prepareStatement("delete from users"); + } +} + + diff --git a/Project/src/main/java/Date10_24/Factory/StatementStrategy.java b/Project/src/main/java/Date10_24/Factory/StatementStrategy.java new file mode 100644 index 0000000..c5e4a0b --- /dev/null +++ b/Project/src/main/java/Date10_24/Factory/StatementStrategy.java @@ -0,0 +1,11 @@ +package Date10_24.Factory; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; + +// 쿼리문을 DAO 클래스에 작성하지 않고 따로 interface를 통해 각자 별도 클래스 생성함 +public interface StatementStrategy { + PreparedStatement makepreparedStatement(Connection connection) throws SQLException; + +} diff --git a/Project/src/main/java/Date10_24/Factory/UserDao.java b/Project/src/main/java/Date10_24/Factory/UserDao.java new file mode 100644 index 0000000..ad7b8be --- /dev/null +++ b/Project/src/main/java/Date10_24/Factory/UserDao.java @@ -0,0 +1,145 @@ +package Date10_24.Factory; + +import Date10_24.domain.User; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +// 중복코드만 따로 빼내서 작성한 코드 (3번째 방식) +public class UserDao { + + private DataSource dataSource; // connectionmaker -> datasource 변경 + + public UserDao(){ // 생성자를 통해 AWS DB의 makeConnection()을 오버라이딩하여 사용 + this.dataSource = new UserDaoFactory().awsDataSource(); + } + public UserDao(DataSource dataSource){ + this.dataSource = dataSource; + } + + // add,delete등 sql문을 사용하는 메서드들은 쿼리문(insert, delete,select 등)만 다르지 구조는 모두 같다 + // 따라서 이러한 중복되는 구조들을 하나의 메서드로 정의한 후 호출하여 사용함 + public void jdbcContextWithStatementStatementstrategy(StatementStrategy st){ + Connection conn = null; + PreparedStatement ps = null; + + try { // 예외처리 + conn = dataSource.getConnection(); // datasource를 사용하게 변경 + ps = new DeleteAllStrategy().makepreparedStatement(conn); + ps.executeUpdate(); + } catch (SQLException e) { + throw new RuntimeException(e); + }finally { // error 발생해도 실행함 + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } + +// public void deleteAll() throws SQLException, ClassNotFoundException { // DB 모든값 삭제 +// jdbcContextWithStatementStatementstrategy(new StatementStrategy() { +// @Override +// public PreparedStatement makepreparedStatement(Connection connection) throws SQLException { +// return connection.prepareStatement(); +// } +// }); +// } + + public int getCount() throws SQLException, ClassNotFoundException { // user테이블의 레코드 개수를 구하기 + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; + try { + conn = dataSource.getConnection(); + ps = conn.prepareStatement("select count(*) from users "); + rs = ps.executeQuery(); + rs.next(); + return rs.getInt(1); + + } catch (SQLException e) { + throw new RuntimeException(e); + } finally { + if(rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } + + public void add(User user) throws ClassNotFoundException, SQLException { + AddStrategy addStrategy = new AddStrategy(user); // User DTO에 저장되어 있는 값 가져옴 + jdbcContextWithStatementStatementstrategy(addStrategy); // add 쿼리문과 추가할 값 가져와서 대입 + + System.out.println("데이터가 insert 됬습니다"); + } + + public User select(String id) throws SQLException, ClassNotFoundException { + + Connection conn = null; + PreparedStatement ps = null; + ResultSet rs = null; // 쿼리문을 저장함 insert문과 달리 excuteQuery() 사용 + User user = null; + try { + conn = dataSource.getConnection(); + ps = conn.prepareStatement("SELECT id,name,password FROM users WHERE id = ?"); + ps.setString(1, id); // id는 get(String id)로 받은 id + rs = ps.executeQuery(); + // rs에는 쿼리 실행 결과가 담겨져 있다. (select * from users where id = 1;) + rs.next(); + // User 생성자를 통해 쿼리문에 id값을 넣어 찾은 id, name,password 값을 저장한다. + return new User(rs.getString("id"), rs.getString("name"), rs.getString("password")); + } + catch (SQLException e) { + throw new RuntimeException(e); + } + finally { + if(rs != null) { + try { + rs.close(); + } catch (SQLException e) { + } + } + if(ps != null){ + try { + ps.close(); + } catch (SQLException e) { + } + } + + if(conn != null){ + try { + conn.close(); + } catch (SQLException e) { + } + } + } + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_24/Factory/UserDaoFactory.java b/Project/src/main/java/Date10_24/Factory/UserDaoFactory.java new file mode 100644 index 0000000..407fef5 --- /dev/null +++ b/Project/src/main/java/Date10_24/Factory/UserDaoFactory.java @@ -0,0 +1,54 @@ +package Date10_24.Factory; + + +// 인터페이스로 받은 것을 어떤것을 UserDaoInterface로 넘겨줄것인지 설정 +// 즉, 인터페이스로 DB별 연결 설정을 나눠놨는데 여기서 메서드별로 다시 DB별로 나누어 +// UserDaoInterface로 해당 DB 연결 설정 값을 보냄 + +// DB설정 파일을 따로 만들지 않고 Bean 파일에서 한번에 사용할수 있도록 리팩토링 + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.jdbc.datasource.SimpleDriverDataSource; + +import javax.sql.DataSource; +import java.util.Map; + +@Configuration +public class UserDaoFactory { + + @Bean + public UserDao awsUserDao(){ + return new UserDao(awsDataSource()); + } + + @Bean + public UserDao localUserDao(){ + return new UserDao(localDataSource()); + } + + @Bean + DataSource awsDataSource(){ + Map env = System.getenv(); + SimpleDriverDataSource dataSource = new SimpleDriverDataSource(); + dataSource.setDriverClass(com.mysql.cj.jdbc.Driver.class); + dataSource.setUrl(env.get("DB_HOST")); + dataSource.setUsername(env.get("DB_USER")); + dataSource.setPassword(env.get("DB_PASSWORD")); + return dataSource; + } + + @Bean + + DataSource localDataSource() { + Map env = System.getenv(); + SimpleDriverDataSource dataSource = new SimpleDriverDataSource(); + dataSource.setDriverClass(com.mysql.cj.jdbc.Driver.class); + dataSource.setUrl("localhost"); + dataSource.setUsername("root"); + dataSource.setPassword("12345678"); + return dataSource; + } + + +} diff --git a/Project/src/main/java/Date10_24/domain/User.java b/Project/src/main/java/Date10_24/domain/User.java new file mode 100644 index 0000000..f83fb85 --- /dev/null +++ b/Project/src/main/java/Date10_24/domain/User.java @@ -0,0 +1,32 @@ +package Date10_24.domain; + +public class User { + private String id; + private String name; + private String password; + + public User() { + } + + public User(String id, String name, String password) { + this.id = id; + this.name = name; + this.password = password; + } + + public String getId() { + return id; + } + + public String getName() { + return name; + } + + public String getPassword() { + return password; + } + + public String toString(){ + return "id = "+this.id + " name = "+this.name+" password = "+this.password; + } +} diff --git a/Project/src/main/java/Date10_25/Algorithm/HashFunction.java b/Project/src/main/java/Date10_25/Algorithm/HashFunction.java new file mode 100644 index 0000000..599cfce --- /dev/null +++ b/Project/src/main/java/Date10_25/Algorithm/HashFunction.java @@ -0,0 +1,16 @@ +package Date10_25.Algorithm; + +public class HashFunction { + public int hash(String key) { + int asciiSum = 0; + for(int i=0; i[] table; // 2차원 배열 리스트 + // ex) 2차원 배열 리스트에 Node형식으로 저장함 + // 1 2 3 + // ["aa",1] ["aaa",2] + // ["bb",2] + + // 내부 클래스 선언 + class Node { // Node DTO [(String)key,(Integer)value] 형식 + private String key; + private Integer value; + + public Node(String key, Integer value) { + this.key = key; + this.value = value; + } + + public String getKey() { + return key; + } + + public Integer getValue() { + return value; + } + } + + + // 디폴트 생성자 + public HashSolution() { // 생성자 + this.size = 10000; + this.table = new ArrayList[size]; + } + + // 생성자 오버로딩 + public HashSolution(int size) { // 생성자 + this.size = size; + this.table = new ArrayList[size]; // 2차원 배열 사이즈 선언 + } + + public int hash(String str) { // hash를 통해 임의의 숫자 구함 + int ascii = 0; + for (int i = 0; i < str.length(); i++) { + ascii += str.charAt(i); + } + return ascii % size; // 1000개 0~999까지의 값 출력 + } + + public Integer get(String key) { // 해시 값 찾기 + List nodes = this.table[hash(key)]; // 2차원 배열 리스트중 hash(key)에 해당하는 배열 가져옴 + // ex) 2차원 배열 리스트의 해당 값을 가져옴 만약 1번일때 + // 1 2 3 + // ["aa",1] ["aaa",2] + // ["bb",2] + + // nodes => ["aa",1],["bb',2] 가져옴 + for (Node node : nodes) { // 2번 반복 + if (key.equals(node.getKey())) { // 입력한 키와 찾아온 키를 비교함 + // ex) 입력된 키가 "bb"일때 + // 1번째 순서일때는 못찾고 2번째 순서일떄 찾는것으로 + // 2번째 node = {"bb",2} , node.getkey() = "bb" + // bb.equals(bb) true + return node.value; // 2번쨰 노드의 객체의 값인 2를 가져옴 + } + } + + return null; + } + + public void insert(String key, Integer value) { + int hashCode = hash(key); // 입력한 문자를 가지고 해시를 통해 임의의 key값 출력 + if (this.table[hashCode] == null) { // 만약 2차원 배열 리스트에 없는 값이라면 + this.table[hashCode] = new ArrayList<>(); // 2차원 배열 리스트 생성 + } + this.table[hashCode].add(new Node(key,value)); // 해당 해쉬 자리에 key,value 객체 저장 + } + + public static void main(String[] args) { + String[] names = new String[]{"DongyeonKang", + "SubinKang", "KwanwunKo", "HyunseokKo", "KyoungdukKoo", "YeonjiGu", "SoyeonKown", "OhsukKwon", "GunwooKim", "KiheonKim", "NayeongKim", "DohyeonKim", "MinkyoungKim", "MinjiKim", "SanghoKim", "SolbaeKim", "YejinKim", "EungjunKim", "JaegeunKim", "JeonghyeonKim", "JunhoKim", "JisuKim", "kimjinah", "HaneulKim", "HeejungKim", "KimoonPark", "EunbinPark", "JeongHoonPark", "JeminPark", "TaegeunPark", "JiwonBae", "SeunggeunBaek", "JihwanByeon", "HeungseopByeon", "JeongHeeSeo", "TaegeonSeo", "SeeYunSeok", "SuyeonSeong", "SeyoelSon", "MinjiSong", "JinwooSong", "hyunboSim", "SominAhn", "JiyoungAhn", "ChangbumAn", "SoonminEom", + "HyeongsangOh", "SuinWoo", "JuwanWoo", "InkyuYoon", "GahyunLee", "DaonLee", "DohyunLee", "SanghunLee", "SujinLee", "AjinLee", "YeonJae", "HyeonjuLee", "HakjunYim", "SeoyunJang", "SeohyeonJang", "JinseonJang", "SujinJeon", "SeunghwanJeon", "DaehwanJung", "JaeHyunJeung", "HeejunJeong", "GukhyeonCho", "MunjuJo", "YejiJo", "ChanminJu", "MinjunChoi", "SujeongChoi", "SeunghoChoi", "AyeongChoi", "GeonjooHan", "JinhyuckHeo", "MinwooHwang", "SieunHwang", + "JunhaHwang"}; + + + HashSolution hashSolution = new HashSolution(200); + hashSolution.insert("Yoonseo", 1); + hashSolution.insert("Seoyoon", 2); + + int result = hashSolution.get("Yoonseo"); + if (result == 1) { + System.out.println("테스트 성공"); + } else { + System.out.printf("테스트 실패 value:%d", result); + } + + result = hashSolution.get("Seoyoon"); + if (result == 2) { + System.out.println("테스트 성공"); + } else { + System.out.printf("테스트 실패 value:%d", result); + } + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date10_27/Algorithm/UnfinishedPlayer.java b/Project/src/main/java/Date10_27/Algorithm/UnfinishedPlayer.java new file mode 100644 index 0000000..d63f1ad --- /dev/null +++ b/Project/src/main/java/Date10_27/Algorithm/UnfinishedPlayer.java @@ -0,0 +1,44 @@ +package Date10_27.Algorithm; + +import java.util.HashMap; +import java.util.Map; + +/* 프로그래머스 완주하지 못한 선수 문제 + 1. 배열로 참가인원 명단 받음 + 2. 완주자 명단 배열로 받음 + 3. 참가인원 명단에서 완주자명단을 제외한 명단을 리턴해줌 + */ +public class UnfinishedPlayer { + public String solution(String[] participant, String[] completion) { + Map memo = new HashMap<>(); + + for (int i = 0; i < participant.length; i++) { + String key = participant[i]; // key에는 participant배열의 값을 넣음 + + if (!memo.containsKey(key)) { // 동명이인 구분을 위해 이미 같은 이름의 키가 존재하지 않다면 + memo.put(key, 0); // [key,0] 대입 + } + + memo.put(key, memo.get(key) + 1); + // 명단이 들어간 자리에는 +1의 값을 넣어줌 + // 즉, 새로 생긴 값이라면 0+1 , 동명이인이라 이미 있는 값이라면 1+1 + // ex) {"홍길동","이순신","홍길동"} 배열 대입 + // ["홍길동",2] ,["이순신",1] + } + + for (int i = 0; i < completion.length; i++) { + String key = completion[i]; + memo.put(key, memo.get(key) - 1); // key의 값에서 -1을 한다. + // {"홍길동","이순신"} 이라면 + // ["홍길동",1] ,["이순신",0] + } + + String person = null; + + for (String key : memo.keySet()) { + if (memo.get(key) == 1) + person = key; + } + return person; + } +} diff --git a/Project/src/main/java/Date10_28/Algorithm/CallBook.java b/Project/src/main/java/Date10_28/Algorithm/CallBook.java new file mode 100644 index 0000000..ff46d0d --- /dev/null +++ b/Project/src/main/java/Date10_28/Algorithm/CallBook.java @@ -0,0 +1,46 @@ +package Date10_28.Algorithm; + +import java.util.HashSet; +import java.util.Set; + +/* 프로그래머스 해시-전화번호 목록 + 1. 전화번호가 적인 값을 배열로 받음 + 2. 각 자리에 있는 전화번호가 다른 전화번호의 접두어인지 판별 + 3. 결과 출력 + */ +public class CallBook { + public Boolean solution(String[] phone_book){ + Set set= new HashSet<>(); + + for(String phone : phone_book) + set.add(phone); // HashSet에 저장 + + for(int i=0; i set = new HashSet<>(); + + for(int num:nums){ // nums의 배열을 1개씩 set에 넣어줌 + // set의 특성을 활용해 중복 제거 + set.add(num); + } + + int answer = (set.size()>count)? count:set.size(); + // set의 크기가 count보다 클경우 count 출력, 작을경우 set 원소개수 출력 + + return answer; + } + + public static void main(String[] args) { + Pokemon p = new Pokemon(); + int result1 = p.choosemax(new int[]{3,1,2,3}); + int result2 = p.choosemax(new int[]{3,3,3,2,2,4}); + int result3 = p.choosemax(new int[]{3,3,3,2,2,2}); + + System.out.println(result1); + System.out.println(result2); + System.out.println(result3); + } +} diff --git a/Project/src/main/java/Date10_31/Algorithm/SearchFull.java b/Project/src/main/java/Date10_31/Algorithm/SearchFull.java new file mode 100644 index 0000000..0a62063 --- /dev/null +++ b/Project/src/main/java/Date10_31/Algorithm/SearchFull.java @@ -0,0 +1,57 @@ +package Date10_31.Algorithm; + +/* 프로그래머스 완전탐색-모의고사 + +1번 수포자가 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ... +2번 수포자가 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ... +3번 수포자가 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ... + +위와 같이 서로 다른 방식으로 문제의 답을 찍어나갈때 3명의 학생중 누가 가장 많이 맞추는지 알아내라 + */ + +import java.util.*; + +public class SearchFull { + public int[] solution(int[] answers) { + + int[] user1 = {1,2,3,4,5}; + int[] user2 = {2,1,2,3,2,4,2,5}; + int[] user3 = {3,3,1,1,2,2,4,4,5,5}; + + int[] temp = {0,0,0}; + + for (int i = 0; i < answers.length; i++) { + if(answers[i] == user1[i%user1.length]) + temp[0]++; + if(answers[i] == user2[i%user2.length]) + temp[1]++; + if(answers[i] == user3[i%user3.length]) + temp[2]++; + } + + int max = Math.max(temp[0], Math.max(temp[1],temp[2])); // 3개의 값 중 최대값 저장 + List maxScore = new ArrayList<>(); + // 최대값이 중복일 경우 리스트에 추가해줌 + for(int i=0; i Arrays + int[] result = new int[maxScore.size()]; + for(int i =0; i maxscorelist = new ArrayList<>(); + int maxscore = Math.max(count[0],Math.max(count[1], count[2])); + + for(int i=0; i int[] + int[] result = maxscorelist.stream() + .mapToInt(Integer::intValue) + .toArray(); + + return result; + } +} diff --git a/Project/src/main/java/Date11_01/Algorithm/AnonymousClassInPrimeNumber.java b/Project/src/main/java/Date11_01/Algorithm/AnonymousClassInPrimeNumber.java new file mode 100644 index 0000000..636d168 --- /dev/null +++ b/Project/src/main/java/Date11_01/Algorithm/AnonymousClassInPrimeNumber.java @@ -0,0 +1,30 @@ +package Date11_01.Algorithm; + +// inteface 포함 +interface Strategy{ + boolean compare(int a, int b); +} + +public class AnonymousClassInPrimeNumber { + boolean isPrime(int num, Strategy stmt) { + for (int i = 2; stmt.compare(i, num); i++) { + System.out.println(i); + if(num % i == 0) return false; + } + return true; + } + + public static void main(String[] args) { + AnonymousClassInPrimeNumber acip = new AnonymousClassInPrimeNumber(); + //람다 사용 + boolean r = acip.isPrime(17,(a,b)->a*a<=b); + +// boolean r = acip.isPrime(17, new Strategy() { +// @Override +// public boolean compare(int a, int b) { +// return a * a <= b; +// } +// }); + + } +} \ No newline at end of file diff --git a/Project/src/main/java/Date11_01/Algorithm/PrimeNumber.java b/Project/src/main/java/Date11_01/Algorithm/PrimeNumber.java new file mode 100644 index 0000000..88a0de4 --- /dev/null +++ b/Project/src/main/java/Date11_01/Algorithm/PrimeNumber.java @@ -0,0 +1,30 @@ +package Date11_01.Algorithm; + + +/* 프로그래머스 소수찾기 +1부터 입력받은 숫자 n 사이에 있는 소수의 개수를 반환하는 문제 +소수는 1과 자기 자신으로만 나누어지는 수를 의미 +(1은 소수가 아니다) +ex) 1~10일때 [2,3,5,7] = 4개가 존재 + + */ + + +public class PrimeNumber { + boolean isPrime(int num){ + // 1은 소수가 아니니 2부터 자기자신보다 1작은수까지 나누어 나머지값을 구한다 + // 만약 이때 나머지 값이 0이 나온다면 소수가 아니므로 false 출력 + for(int i = 2; i a < b)); +// System.out.println(tcp.isPrime(17, (a, b)-> a < b/2)); +// System.out.println(tcp.isPrime(19, (a, b)-> a * a < b)); +// +//// @Override +//// boolean b = tcp.isPrime(17, new StatementStrategy() { +//// public boolean compare(int a, int b) { +//// return a * a <= b; +//// } +//// }); +// +// } +// } \ No newline at end of file diff --git a/Project/src/main/java/Date11_02/Algorithm/PrimeNumber.java b/Project/src/main/java/Date11_02/Algorithm/PrimeNumber.java new file mode 100644 index 0000000..3b3976c --- /dev/null +++ b/Project/src/main/java/Date11_02/Algorithm/PrimeNumber.java @@ -0,0 +1,44 @@ +package Date11_02.Algorithm; + +import java.util.ArrayList; +import java.util.List; + +/* 프로그래머스 소수찾기 (에라토스테네스의 체를 통한 풀이) + 소수가 아닌 값을 제외시켜 최종적으로 소수인 값만 남기는 방식 + + 이전에 했던 코드가 O(N)이라면 에라토스테네스의 체는 O(Log N)정도의 속도가 나온다. + */ +public class PrimeNumber { + + // 리스트를 통한 풀이 + public int solution(int num){ + List nums = new ArrayList<>(); + + // 1은 소수가 아니므로 2부터 시작 + for(int i =2; i<=num; i++){ + nums.add(i); + } + + // removeif( ) list의 메서드로 조건문을 통해 해당하는 값은 제거시킨다. + + // 2부터 num-1번값까지 + // 일반 for문으로 i<=num으로 돌리면 num값이 클경우 너무 많은 반복을 하게됨 + // 따라서 i의 제곱이 num보다 작거나 같을때까지 반복하게 되면 모든 소수를 찾을 수 있고 반복횟수도 적어짐 + // ex) num = 10일때, i는 2,3만 들어갈수 있음 + // + for(int i=2; i*i<=num; i++) { + for (int j = 0; j < nums.size(); j++) { + // 배수이면서 자기자신은 아니여야 함 + if (nums.get(j) % i == 0 && nums.get(j) != i) { + nums.remove(j); + } + } + } + return nums.size(); + } + + public static void main(String[] args) { + PrimeNumber p = new PrimeNumber(); + System.out.println(p.solution(10)); // 시간초과 발생 + } +} diff --git a/Project/src/main/java/Date11_03/Algorithm/PrimeNumber.java b/Project/src/main/java/Date11_03/Algorithm/PrimeNumber.java new file mode 100644 index 0000000..96c2b5b --- /dev/null +++ b/Project/src/main/java/Date11_03/Algorithm/PrimeNumber.java @@ -0,0 +1,47 @@ +package Date11_03.Algorithm; + + +import java.util.Arrays; + +/* 프로그래머스 소수찾기 (에라토스테네스의 체를 통한 풀이) + 이전에 했던 리스트를 통한 에라토스테네스의 체를 통한 풀이는 속도가 느려 통과가 안되는 문제가 발생했다 + 따라서 배열을 통해 속도를 좀 더 높힐 수 있도록 했다. + */ +public class PrimeNumber { + public int solution(int num) { + + int count = 0; + boolean[] result = new boolean[num+1]; // 0~n까지 크기 + Arrays.fill(result,true); // 배열 true로 채움(boolean 배열의 초기값은 false라 굳이 안채워줘도 되지만 라이브러리 사용을 위해 사용) + + + // 0과 1은 소수가 아니므로 false를 넣어준다. + result[0] = false; + result[1] = false; + + // n의 제곱근보다 작은 정수의 배수들만 지우면 n보다 작은 소수만 남게 됨 + for(int i= 2; i*i<=num; i++){ // 2~7까지의 배수값 구함 7*7 = 49 + + // j = i*i로 해줘야 자기 자신값은 제외가 됨. 2,3,5,7은 소수이므로 자기 자신의 값은 제외해야함 + // ex) i=2일때, 2는 소수이므로 4부터 시작하여 4,6,8,10... 값을 false로 대입 + // i=4일때, 어차피 4는 i=2일때 false를 대입했으므로 자기 자신의 값을 신경안써줘도 됨 + for(int j =i*i; j0){ + sumOfDigit += x%10; + x = x/10; + } + + if(num%sumOfDigit == 0){ + return true; + } + + return false; + } + + //String으로 값을 받아 계산하는 방식 + public boolean solution2(int x){ + String[] num = String.valueOf(x).split(""); // 입력받은 숫자를 문자열 배열 한자리씩 나눔 + + int sum = 0; + for(String s : num){ // 문자열 배열에 저장된 자릿수의 값들을 한개씩 뽑아 모두 더함 + sum += Integer.parseInt(s); + } + + if(x%sum == 0){ + return true; + } + + return false; + } + + public static void main(String[] args) { + Harshad hs = new Harshad(); + System.out.println(hs.solution2(10)); + System.out.println(hs.solution2(11)); + } +} diff --git a/Project/src/main/java/Date11_07/Algorithm/Harshad2.java b/Project/src/main/java/Date11_07/Algorithm/Harshad2.java new file mode 100644 index 0000000..dc18664 --- /dev/null +++ b/Project/src/main/java/Date11_07/Algorithm/Harshad2.java @@ -0,0 +1,71 @@ +package Date11_07.Algorithm; + +import java.util.*; + +/* PriorityQueue() 사용해서 푸는 법 + + 프로그래머스 나누어 떨어진느 숫자 배열 + 1. 배열을 통해 숫자 값들을 입력받음 + 2. 나누고 싶은 값을 설정함 + 3. 배열에 있는 값들을 나누고 싶은 값을 통해 나눔 + 4. 이때 나머지가 없이 딱 나누어지는 값을 배열에 넣어 리턴함 + 5. 만약 나머지가 없이 딱 나누어 떨어지는 값이 없을경우 -1 리턴 + */ +public class Harshad2 { + + // 기본 풀이 (리스트로 값 받은 후 배열에 저장하여 반환) + public int[] solution(int[] arr,int divisor){ + + List templist = new ArrayList<>(); + + for(int i=0; i list = new PriorityQueue<>(); + for (int i = 0; i < arr.length; i++) { + if (arr[i] % divisor == 0) list.add(arr[i]); + } + + if(list.size() == 0) return new int[]{-1}; + + // list를 Array로 바꾸기 + int[] answer = new int[list.size()]; // 배열의 크기를 list크기만큼 설정 + int idx = 0; + while(!list.isEmpty()){ // 리스트가 비어있지 않을경우 + answer[idx++] = list.poll(); // 배열에 리스트를 넣는다. + } + return answer; + } + + public static void main(String[] args) { + Harshad2 hs = new Harshad2(); + int[] arr ={5,9,7,10}; + int[] arr2 ={2,36,1,3}; + int[] arr3 = {3,2,6}; + System.out.println(Arrays.toString(hs.solution2(arr,5))); + System.out.println(Arrays.toString(hs.solution2(arr2,1))); + System.out.println(Arrays.toString(hs.solution2(arr3,10))); + } +} diff --git a/Project/src/main/java/Date11_08/Alogrithm/SimpleSearch.java b/Project/src/main/java/Date11_08/Alogrithm/SimpleSearch.java new file mode 100644 index 0000000..1e2a592 --- /dev/null +++ b/Project/src/main/java/Date11_08/Alogrithm/SimpleSearch.java @@ -0,0 +1,51 @@ +package Date11_08.Alogrithm; + +import com.fasterxml.jackson.core.util.BufferRecycler; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.Buffer; +import java.util.Arrays; + +/* + CodeUp 3001 데이터 탐색 + 1. 몇개의 데이터를 입력할 것인지 n 입력 + 2. n개의 갯수만큼 데이터 입력 + 3. 찾고 싶은 값을 입력 + 4. 찾고 싶은 값의 위치를 출력 만약 없는 값이라면 -1 반환 + */ +public class SimpleSearch { + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + public int solution(int num) throws IOException { + int[] nums = new int[num]; // 입력한 값들 저장소의 크기 설정 + String[] temp = br.readLine().split(" "); + + for(int i=0; i targetnum) // midnum이 targetnum 보다 클 경우 + endIdx = midIdx; // 인덱스 끝점을 midIdx로 바꿔줌 + + else if(midnum < targetIdx) // midnum이 targetnum 보다 작을 경우 + startIdx = midIdx; // 인덱스 시작점을 midIdx로 바꿔줌 + + else // midnum이 targetnum이랑 같을경우 + targetIdx += midIdx; // 찾을 index가 midIdx이므로 targetIdx에 midIdx 저장 + } + return targetIdx; + } + + public static void main(String[] args) throws IOException { + int num = Integer.parseInt(br.readLine()); + SimpleSearch s = new SimpleSearch(); + System.out.println(s.solution(num)); + } +} diff --git a/Project/src/main/java/Date11_09/Algorithm/SelectionSort.java b/Project/src/main/java/Date11_09/Algorithm/SelectionSort.java new file mode 100644 index 0000000..9100080 --- /dev/null +++ b/Project/src/main/java/Date11_09/Algorithm/SelectionSort.java @@ -0,0 +1,47 @@ +package Date11_09.Algorithm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; + +/* 선택정렬(1) + index = 0번부터 제일 작은 값으로 채워 나감 + ex) index = 0 1 2 3 4 + value = 5 7 3 1 2 일떄 + index 0번째 자리의 값을 다른 index 값과 모두 비교해서 제일 작은 값으로 바꿈 즉, 1과 자리를 바꿈 + */ + +public class SelectionSort { + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + public int[] solution(int[] arr){ + int[] result = arr; + + for(int i=0; iresult[j]) + minidx = j; + } + int temp = result[i]; + result[i] = result[minidx]; + result[minidx] = temp; + } + + return result; + } + + + public static void main(String[] args) throws IOException { + SelectionSort s = new SelectionSort(); + String[] temp = br.readLine().split(" "); + int[] arr = new int[temp.length]; + + for(int i=0; i a>b))); + System.out.println(Arrays.toString(s.solution(arr,(a,b) -> ab; +// } +// }); + + } +} diff --git a/Project/src/main/java/Date11_09/Algorithm/SelectionSort3.java b/Project/src/main/java/Date11_09/Algorithm/SelectionSort3.java new file mode 100644 index 0000000..7505c92 --- /dev/null +++ b/Project/src/main/java/Date11_09/Algorithm/SelectionSort3.java @@ -0,0 +1,75 @@ +package Date11_09.Algorithm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.Arrays; +import java.util.function.BiFunction; +import java.util.function.BiPredicate; + +/* /* 선택정렬(3) - ByFunction 사용해서 구현해보기 + index = 0번부터 제일 작은 값으로 채워 나감 + ex) index = 0 1 2 3 4 + value = 5 7 3 1 2 일떄 + index 0번째 자리의 값을 다른 index 값과 모두 비교해서 제일 작은 값으로 바꿈 즉, 1과 자리를 바꿈 + */ +public class SelectionSort3 { + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + // BiFunction을 사용한 풀이 + public int[] solution(int[] arr, BiFunction stmt){ + int[] result = arr; + + for(int i=0; i을 사용해야하지만 default값이 boolean이기 때문에 Boolean은 생략 가능 + public int[] solution2(int[] arr, BiPredicate stmt){ + int[] result = arr; + + for(int i=0; i biFunction = (a,b) -> a>b; + BiPredicate biPredicate = (a,b) -> a biFunction2 = (a,b) -> a numlist = new ArrayList<>(); + numlist.add(nums[0]); // 이전값과 다음값을 비교하기 위해 미리 처음 숫자를 넣어줌 + + // list 사이즈의 -1의 값이 새로들어오는 값과 같다면 추가안함 + // ex) {1,1,3,1}을 입력받을때 list에 처음값 1을 집어넣은 상태에서 반복문 실행 + // i = 1일때, listsize = 1이므로 numlist.get(1-1)의 값인 1을 가져와 nums[1]의 값인 1과 비교함 + // 이때 값이 중복되므로 list에 넣지 않음 + // i = 2일때, numlist.get(1-1)의 값인 1을 가져와 nums[2]의 값인 3과 비교 후 다르므로 list저장 + // i = 3일때, nulist.get(2-1)의 값인 3을 가져와 nums[3]의 값인 1과 비교 후 다르므로 list에 저장 + + for(int i=1; i numlist = new Stack<>(); + numlist.push(nums[0]); + + for (int i = 1; i < nums.length; i++) { + if(numlist.peek() != nums[i]) // 스택에 있는 가장 높은 값을 가져와 비교함 + numlist.push(nums[i]); + } + + int[] result = new int[numlist.size()]; + for (int i = numlist.size()-1; i>=0; i--) { // 스택은 후입선출이기때문에 거꾸로 넣어줘야함 + result[i] = numlist.pop(); + } + + return result; + } + + public static void main(String[] args) { + NoOverlap2 no = new NoOverlap2(); + System.out.println(Arrays.toString(no.solution(new int[]{4,4,4,3,3}))); + System.out.println(Arrays.toString(no.solution(new int[]{1, 1, 3, 3, 0, 1, 1}))); + } +} diff --git a/Project/src/main/java/Date11_15/Algorithm/QuickSort.java b/Project/src/main/java/Date11_15/Algorithm/QuickSort.java new file mode 100644 index 0000000..c2c6bbc --- /dev/null +++ b/Project/src/main/java/Date11_15/Algorithm/QuickSort.java @@ -0,0 +1,56 @@ +package Date11_15.Algorithm; + +import java.util.ArrayList; +import java.util.List; + +// 재귀함수를 통한 퀵 정렬 - List로 풀기 +public class QuickSort { + + public List merge(List left,List mid,List right){ + List answer = new ArrayList<>(); + answer.addAll(left); + answer.addAll(mid); + answer.addAll(right); + + return answer; + } + + public List sort(List arr){ + + // 재귀 탈출 조건 + if(arr.size()<=1) return arr; // mid보다 값이 모두 작거나 커서 한쪽으로 쏠려 한쪽에는 아예 들어가지 않는 경우도 생기고 + // 1개의 값만 들어가는 경우도 생긴다. 1개만 들어가면 더이상 비교를 할 수 없기에 1이하로 하여 재귀를 빠져나오도록 한다. + + // 1. 기준값 뽑는 로직 구현 + int pivot = arr.get(arr.size()/2); // index = 4 , arr[4] = 5 + + // 2. 기준값 기준으로 왼쪽 오른쪽으로 나누어 담는 로직 구현 + List left = new ArrayList<>(); + List right = new ArrayList<>(); + List mid = new ArrayList<>(); + + for(int i=0; ipivot) + right.add(arr.get(i)); + else + mid.add(arr.get(i)); + } + + // list를 합치는 연산 + return merge(sort(left),mid,sort(right)); + } + + public static void main(String[] args) { + int[] arr = {20,18,5,19,5,25,40,50}; // 8 + List al = new ArrayList<>(); + for(int i =0; i= 97 && (int)c <= 122) { // 소문자 일때 + int result = c+num; + if(result >122){ + result -= 122; + return (char)((96+result)); + } + return (char) ((c + num)); + } + else if((int)c>=65 && (int)c<=90) { // 대문자 일때 + int result = c+num; + if(result >90){ + result -= 90; + return (char)((64+result)); + } + return (char) ((c + num)); + } + else // 공백일 경우 + return c; + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + String result = ""; + + System.out.print("문자열을 입력하세요 :"); + char[] str = br.readLine().toCharArray(); + for(int i=0; i (26)%26 + 97 => 0+97 => 97 (a) + // 즉, 입력받은 문자열을 초기값인 a로 빼고 n만큼 더해 얼마나 증가가 되는지 계산한후 + // 소문자의 전체 갯수인 26개로 나머지값을 구함(소문자 아스키 코드는 97~122번 사이에 존재하므로 그 이상이 되면 다른 문자가 출력됨) + // 만약 26으로 나머지 값을 구하지 않으면 26+97 = 123으로 { 문자가 출력됨 따라서 이를 방지하고자 소문자 범위 내에서 계산되도록 설정 + // 마지막으로 초기값 97(a)를 더해 증가된 문자를 출력함 + } + else if(Character.isUpperCase(c)) { // 대문자 일때 + c = (char)((c-'A'+n)%26 + 'A'); + } + result += c; + } + + return result; + } + + + public static void main(String[] args) { + CaesarPassword2 cp = new CaesarPassword2(); + System.out.println(cp.solution("AB",1)); + System.out.println(cp.solution("z",1)); + System.out.println(cp.solution("a B z",4)); + } +} diff --git a/Project/src/main/java/Date11_23.Algorithm/Recursion.java b/Project/src/main/java/Date11_23.Algorithm/Recursion.java new file mode 100644 index 0000000..83cdca5 --- /dev/null +++ b/Project/src/main/java/Date11_23.Algorithm/Recursion.java @@ -0,0 +1,29 @@ +package Date11_23.Algorithm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/* 재귀함수 문제 - 코드업 1851번 + n을 입력받아 n개의 별을 출력하기(재귀 사용) + */ +public class Recursion { + + public String solution(int num){ + + if(num == 0){ + return ""; + } + + return "*" + solution(num - 1); + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + System.out.print("n의 값을 입력하세요 : "); + int num = Integer.parseInt(br.readLine()); + Recursion r = new Recursion(); + System.out.println(r.solution(num)); + } +} diff --git a/Project/src/main/java/Date11_23.Algorithm/Recursion2.java b/Project/src/main/java/Date11_23.Algorithm/Recursion2.java new file mode 100644 index 0000000..0a9b1b3 --- /dev/null +++ b/Project/src/main/java/Date11_23.Algorithm/Recursion2.java @@ -0,0 +1,30 @@ +package Date11_23.Algorithm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/* 재귀함수(2) + 한 정수n을 입력받아 1부터 n까지의 정수 합을 출력하라 + */ +public class Recursion2 { + public int solution(int num){ + if(num == 0){ + return 0; + } + + return num + solution(num-1); + } + + + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + System.out.print("n의 값을 입력하세요 : "); + int num = Integer.parseInt(br.readLine()); + + Recursion2 r2 = new Recursion2(); + System.out.println(r2.solution(num)); + } +} diff --git a/Project/src/main/java/Date11_23.Algorithm/Recursion3.java b/Project/src/main/java/Date11_23.Algorithm/Recursion3.java new file mode 100644 index 0000000..d6759ef --- /dev/null +++ b/Project/src/main/java/Date11_23.Algorithm/Recursion3.java @@ -0,0 +1,32 @@ +package Date11_23.Algorithm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/* 재귀함수(3) 코드업 1854번 문제 + 재귀로 각 자리 수의 합 리턴하기 + */ +public class Recursion3 { + public int solution(int num){ + if(num == 0){ + return 0; + } + + int result = num % 10; + + return result + solution(num/10); + } + + + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + System.out.print("n의 값을 입력하세요 : "); + int num = Integer.parseInt(br.readLine()); + + Recursion3 r3 = new Recursion3(); + System.out.println(r3.solution(num)); + } +} diff --git a/Project/src/main/java/Date11_23.Algorithm/Recursion4.java b/Project/src/main/java/Date11_23.Algorithm/Recursion4.java new file mode 100644 index 0000000..16a3b7c --- /dev/null +++ b/Project/src/main/java/Date11_23.Algorithm/Recursion4.java @@ -0,0 +1,22 @@ +package Date11_23.Algorithm; + +/* 재귀(4) 코드업 1855번 + 재귀로 n번째 피보나치 수 리턴하기 + */ +public class Recursion4 { + public static void main(String[] args) { + // 0부터 8까지의 피보나치 수 모두 출력 + for (int i=0; i<9; i++) { + System.out.printf("%d\t", fibo(i)); + } + } + + public static int fibo(int n) { + // 전달받은 값과 동일한 값을 리턴한다면 계산할 필요가 없으므로 중단 + if (n <= 1) { + return n; + } else { + return fibo(n-2) + fibo(n-1); + } + } +} diff --git a/Project/src/main/java/Date11_25/Algorithm/GCD.java b/Project/src/main/java/Date11_25/Algorithm/GCD.java new file mode 100644 index 0000000..0bf15ef --- /dev/null +++ b/Project/src/main/java/Date11_25/Algorithm/GCD.java @@ -0,0 +1,37 @@ +package Date11_25.Algorithm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +/* 최대공약수 구하기(GCD: Greatest Common Divisor) - 코드업 2623번 문제 + 2개의 값을 입력받아 2개의 최대 공약수를 얻을 수 있다. + + 유클리드 호제법 공식 사용하여 최대공약수를 구한다. + 유클리드 호제법 : https://ko.wikipedia.org/wiki/%EC%9C%A0%ED%81%B4%EB%A6%AC%EB%93%9C_%ED%98%B8%EC%A0%9C%EB%B2%95 + */ +public class GCD { + public static int solution(int num, int num2){ + /* 만약 70,42를 입력받는다고 하면 + 70 % 42 = 28 -- num = 70, num2 = 42 + 42 % 28 = 14 -- num = 42, num2 = 28 + 28 % 14 = 0 -- num = 28, num2 = 14 + 14 % 0 -- num = 14, num2 = 0 이므로 재귀함수가 빠져나옴과 동시에 num값을 반환함 + */ + if(num2 == 0) return num; + + return solution(num2,num%num2); + } + + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + System.out.print("첫번째 수를 입력하세요:"); + int num = Integer.parseInt(br.readLine()); + System.out.print("두번째 수를 입력하세요:"); + int num2 = Integer.parseInt(br.readLine()); + + System.out.println(solution(num>num2 ? num:num2,num>num2 ? num2:num)); // 큰값이 첫번째 매개변수로 갈 수 있도록 구성 + + } +} diff --git a/Project/src/test/java/Date10_20/Algorithm/stackTest.java b/Project/src/test/java/Date10_20/Algorithm/stackTest.java new file mode 100644 index 0000000..6928263 --- /dev/null +++ b/Project/src/test/java/Date10_20/Algorithm/stackTest.java @@ -0,0 +1,78 @@ +package Date10_20.Algorithm; + + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.EmptyStackException; +import java.util.Stack; + +import static org.junit.jupiter.api.Assertions.*; + +class stackTest { + stack st = new stack(); + + @BeforeEach // 무조건 제일 먼저 실행하고 시작함(공통값을 넣을때 주로 사용) + void setUp() { // 각 테스트가 실행되기 전에 실행되어 테스트별 구분함 + System.out.println("before each"); + } + + @Test + @DisplayName("push가 잘되는지") + void push(){ + st.push(10); + st.push(20); + Integer[] arr = st.getArr(); + + assertEquals(20,arr[1]); + assertEquals(10,arr[0]); + } + + @Test + void pushAndPop(){ + st.push(10); + st.push(20); + + assertEquals(20, st.pop()); + assertEquals(10, st.pop()); + // st.pop() 비어 있을땐? + // Exception 예외의 검증 + assertThrows(RuntimeException.class,()->{ + st.pop(); + }); +// st.pop(); + } + + @Test + void isEmpty() { + assertTrue(st.isEmpty()); + st.push(20); + assertFalse(st.isEmpty()); + st.pop(); + assertTrue(st.isEmpty()); + } + + @Test + void realStack() { + // 자바 스택 구현채 (미리 해놓은거) + Stack st = new Stack<>(); + assertThrows(EmptyStackException.class, ()->{ + st.pop(); + }); +// st.pop(); + + } + + @Test + void peek() { + stack st = new stack(); + // 스택이 비었는데 peek 할 때 + assertThrows(EmptyStackException.class,()->{ + st.peek(); + }); + st.push(10); + int peeked = st.peek(); + assertEquals(10,peeked); + } +} diff --git a/Project/src/test/java/Date10_20/Factory/UserDaoTest.java b/Project/src/test/java/Date10_20/Factory/UserDaoTest.java new file mode 100644 index 0000000..7341b94 --- /dev/null +++ b/Project/src/test/java/Date10_20/Factory/UserDaoTest.java @@ -0,0 +1,85 @@ +package Date10_20.Factory; + +import Date10_20.dao.Factory.UserDaoFactory; +import Date10_20.dao.Factory.UserDao; +import Date10_20.domain.User; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@ExtendWith(SpringExtension.class) // spring에서 테스트 하기 위한 설정 +@ContextConfiguration(classes = UserDaoFactory.class) +class UserDaoFactoryTest { + // 싱글톤을 위해 Autowired 사용 + @Autowired // 새로운 객체를 사용하지 않고 이전에 사용했던 객체의 주소를 그대로 사용한다는 설정 + // new 객체 생성을 한번만 사용함(고정값) + ApplicationContext context; // Spring ApplicationContext를 사용하기 위해서는 + // @ExtendWith 과 @ContextConfiguration를 추가해줘야 한다. + UserDao userDao; + User user1; + User user2; + User user3; + + @BeforeEach + void setUp(){ // 각각의 테스트 시작전 필수로 동작하는 부분 + userDao = context.getBean("awsUserDao", UserDao.class); + user1 = new User("1","홍길동","1234"); + user2 = new User("2","이순신","4567"); + user3 = new User("3","세종","7896"); + } + @Test + void addAndSelect() throws ClassNotFoundException, SQLException { + + // .deleteAll() 오류 검증 + userDao.deleteAll(); + Assertions.assertThat(0).isEqualTo(userDao.getCount()); + + String id = "3"; + userDao.add(user3); + Assertions.assertThat(1).isEqualTo(userDao.getCount()); + + User user = userDao.select(id); + + Assertions.assertThat("세종").isEqualTo(user.getName()); + // assertEquals("Spring",user.getName()); + } + @Test + //.count test만들기 + void count() throws SQLException, ClassNotFoundException { + + UserDao userDao = context.getBean("awsUserDao", UserDao.class); + //.deleteAll() 오류 검증 + userDao.deleteAll(); + assertEquals(0, userDao.getCount()); + + userDao.add(user1); + assertEquals(1, userDao.getCount()); + userDao.add(user2); + assertEquals(2, userDao.getCount()); + userDao.add(user3); + assertEquals(3, userDao.getCount()); + } + + + @Test + @DisplayName("") + void findById() { + assertThrows(EmptyResultDataAccessException.class, ()-> { + userDao.select("30"); // 데이터가 없을때 ResultSet이 빈 경우 null로 오류가 난다. + }); + } + + +} \ No newline at end of file diff --git a/Project/src/test/java/Date10_20/UserDaoInterfaceTest.java b/Project/src/test/java/Date10_20/UserDaoInterfaceTest.java new file mode 100644 index 0000000..409c7c5 --- /dev/null +++ b/Project/src/test/java/Date10_20/UserDaoInterfaceTest.java @@ -0,0 +1,24 @@ +package Date10_20; + + +import Date10_20.dao.Interface.UserDaoInterface; +import Date10_20.domain.User; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.sql.SQLException; + + +// 3번째 방식 테스트 +class UserDaoTest { + @Test + void addAndSelect() throws ClassNotFoundException, SQLException { + UserDaoInterface userDao = new UserDaoInterface(); + String id = "12"; + User user = new User(id,"test","1234"); // user 값을 DTO에 저장함 + userDao.add(user); + + User selectedUser = userDao.select(id); // DTO에 저장되어 있는 데이터를 가져와 비교함 + Assertions.assertEquals("test",selectedUser.getName()); + } +} \ No newline at end of file diff --git a/Project/src/test/java/Date10_20/UserDaoTest.java b/Project/src/test/java/Date10_20/UserDaoTest.java new file mode 100644 index 0000000..d99ad11 --- /dev/null +++ b/Project/src/test/java/Date10_20/UserDaoTest.java @@ -0,0 +1,22 @@ +//package Date10_20; +// +//import Date10_20.dao.Abstract.AWSUserDaoImpl; +//import Date10_20.domain.User; +//import org.junit.jupiter.api.Assertions; +//import org.junit.jupiter.api.Test; +// +//import java.sql.SQLException; +// +//class UserDaoTest { +// +// @Test +// void addAndSelect() throws ClassNotFoundException, SQLException { +// AWSUserDaoImpl userDao = new AWSUserDaoImpl(); +// String id = "10"; +// User user = new User(id,"test","1234"); // user 값을 DTO에 저장함 +// userDao.add(user); +// +// User selectedUser = userDao.select(id); // DTO에 저장되어 있는 데이터를 가져와 비교함 +// Assertions.assertEquals("test",selectedUser.getName()); +// } +//} \ No newline at end of file diff --git a/Project/src/test/java/Date10_21/Algorithm/Factory/JdbcUserDaoTest.java b/Project/src/test/java/Date10_21/Algorithm/Factory/JdbcUserDaoTest.java new file mode 100644 index 0000000..b0dab4b --- /dev/null +++ b/Project/src/test/java/Date10_21/Algorithm/Factory/JdbcUserDaoTest.java @@ -0,0 +1,88 @@ +package Date10_21.Algorithm.Factory; + +import Date10_20.dao.Factory.UserDao; +import Date10_20.dao.Factory.UserDaoFactory; +import Date10_20.domain.User; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit.jupiter.SpringExtension; + +import java.sql.SQLException; + +import static org.junit.jupiter.api.Assertions.*; + +@ExtendWith(SpringExtension.class) // spring에서 테스트 하기 위한 설정 +@ContextConfiguration(classes = UserDaoFactory.class) +class JdbcUserDaoTest { + // 싱글톤을 위해 Autowired 사용 + @Autowired // 새로운 객체를 사용하지 않고 이전에 사용했던 객체의 주소를 그대로 사용한다는 설정 + // new 객체 생성을 한번만 사용함(고정값) + ApplicationContext context; // Spring ApplicationContext를 사용하기 위해서는 + // @ExtendWith 과 @ContextConfiguration를 추가해줘야 한다. + Date10_20.dao.Factory.UserDao userDao; + User user1; + User user2; + User user3; + + @BeforeEach + void setUp(){ // 각각의 테스트 시작전 필수로 동작하는 부분 + userDao = context.getBean("awsUserDao", Date10_20.dao.Factory.UserDao.class); + user1 = new User("1","홍길동","1234"); + user2 = new User("2","이순신","4567"); + user3 = new User("3","세종","7896"); + System.out.println("Before Each"); + } + @Test + @DisplayName("insert/select 테스트") + void addAndSelect() throws ClassNotFoundException, SQLException { + + // .deleteAll() 오류 검증 + userDao.deleteAll(); + Assertions.assertThat(0).isEqualTo(userDao.getCount()); + + String id = "3"; + userDao.add(user3); + Assertions.assertThat(1).isEqualTo(userDao.getCount()); + + User user = userDao.select(id); + + Assertions.assertThat("세종").isEqualTo(user.getName()); + // assertEquals("Spring",user.getName()); + } + @Test + //.count test만들기 + @DisplayName("count 테스트") + void count() throws SQLException, ClassNotFoundException { + + Date10_20.dao.Factory.UserDao userDao = context.getBean("awsUserDao", UserDao.class); + //.deleteAll() 오류 검증 + userDao.deleteAll(); + assertEquals(0, userDao.getCount()); + + userDao.add(user1); + assertEquals(1, userDao.getCount()); + userDao.add(user2); + assertEquals(2, userDao.getCount()); + userDao.add(user3); + assertEquals(3, userDao.getCount()); + } + + +/* @Test + void findById() { + assertThrows(EmptyResultDataAccessException.class, () -> { + userDao.select("1"); + }); + } + + */ + + +} \ No newline at end of file diff --git a/Project/src/test/java/Date10_21/Algorithm/StackSolutionTest.java b/Project/src/test/java/Date10_21/Algorithm/StackSolutionTest.java new file mode 100644 index 0000000..bd42529 --- /dev/null +++ b/Project/src/test/java/Date10_21/Algorithm/StackSolutionTest.java @@ -0,0 +1,17 @@ +package Date10_21.Algorithm; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class StackSolutionTest { + + @Test + @DisplayName("괄호 구분") + void bracket(){ + StackSolution s = new StackSolution(); + assertTrue(s.solution("{}()[](({}))")); + assertFalse(s.solution("{}()[](({))")); + } +} \ No newline at end of file diff --git a/Project/src/test/java/Date10_21/Algorithm/bracketTest.java b/Project/src/test/java/Date10_21/Algorithm/bracketTest.java new file mode 100644 index 0000000..6a95b4a --- /dev/null +++ b/Project/src/test/java/Date10_21/Algorithm/bracketTest.java @@ -0,0 +1,21 @@ +package Date10_21.Algorithm; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class bracketTest { + + @Test + @DisplayName("괄호가 잘 풀리는지") + void bracket(){ + bracket sb = new bracket(); + assertFalse(sb.result("()())")); + assertFalse(sb.result(")()()(")); + assertTrue(sb.result("()()")); + assertTrue(sb.result("((()()))")); + assertTrue(sb.result("((((((((((()))))))))))")); + assertFalse(sb.result("(()(")); + } +} \ No newline at end of file diff --git a/Project/src/test/java/Date10_27/Algorithm/UnfinishedPlayerTest.java b/Project/src/test/java/Date10_27/Algorithm/UnfinishedPlayerTest.java new file mode 100644 index 0000000..0449adc --- /dev/null +++ b/Project/src/test/java/Date10_27/Algorithm/UnfinishedPlayerTest.java @@ -0,0 +1,22 @@ +package Date10_27.Algorithm; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +class UnfinishedPlayerTest { + + @Test + @DisplayName("명단, 완주명단 입력") + void runner(){ + UnfinishedPlayer up = new UnfinishedPlayer(); + String[] participant = {"mislav", "stanko", "mislav", "ana"}; + String[] completion = {"stanko", "ana", "mislav"}; + + String result = up.solution(participant,completion); + + Assertions.assertEquals("mislav",result); + } +} \ No newline at end of file diff --git a/Project/src/test/java/Date10_31/Algorithm/SearchFull2Test.java b/Project/src/test/java/Date10_31/Algorithm/SearchFull2Test.java new file mode 100644 index 0000000..19a6aa4 --- /dev/null +++ b/Project/src/test/java/Date10_31/Algorithm/SearchFull2Test.java @@ -0,0 +1,33 @@ +package Date10_31.Algorithm; + +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.*; + + + +class SearchFull2Test { + + @Test + @DisplayName("제일많이 맞춘사람 1명일때") + void onecheck(){ + SearchFull2 sf = new SearchFull2(); + + int[] answers = {1,2,3,4,5}; + + assertEquals("[1]",Arrays.toString(sf.solution(answers))); + } + + @Test + @DisplayName("제일많이 맞춘사람 1명 이상 일때") + void twocheck(){ + SearchFull2 sf = new SearchFull2(); + + int[] answers2 = {1,3,2,4,2}; + + assertEquals("[1, 2, 3]",Arrays.toString(sf.solution(answers2))); + } +} \ No newline at end of file diff --git a/README.md b/README.md index 4c8a22f..228a64a 100644 --- a/README.md +++ b/README.md @@ -1 +1,105 @@ -# 자바 공부 +### 🦁 멋쟁이사자처럼 백엔드 + +## 목적 : 자바 알고리즘 + +# 🗓 공부 일정 +
+ +📄 실습 정리 블로그 : https://velog.io/@qowl880/series/%EC%9E%90%EB%B0%94-%EC%8B%A4%EC%8A%B5 + +📄 알고리즘 정리 블로그 : https://velog.io/@qowl880/series/%EC%95%8C%EA%B3%A0%EB%A6%AC%EC%A6%98 + +- 2022-10-04 : Git + 알고리즘 + +- 2022-10-05 : Intellij Git 사용 + 자바란? + interface 의존성과 다형성을 통한 예제 문제 + +- 2022-10-06 : List/Set/Map + File(파일 입출력) + +- 2022-10-07 : Project(대용량데이터처리) + +- 2022-10-11 : Aws + docker + Mysql 연결 + +- 2022-10-12 : 알고리즘[max,min 구하기] + 대용량 데이터 처리 + +- 2022-10-13 : 알고리즘[버블정렬] + 대용량 데이터 처리(Mysql에 파일로 데이터 삽입) + +- 2022-10-14 : 알고리즘[삽입정렬] + Mysql(기초 문법) + TDD + +- 2022-10-17 : 알고리즘[For문 별찍기] + Java/Mysql 연결(Insert) + +- 2022-10-18 : 알고리즘[For문 사각형 만들기] + Java/Mysql 연결(리팩토링 : 중복 코드 분리, Abstract하여 DB별 설정 나누기) + +------------------------------------------ Spring 시작 ------------------------------------------ +
Spring은 별도 Repository를 통해 공부를 진행 +https://github.com/Bae-Ji-Won/Spring-Study + +- 2022-10-19 : 알고리즘[Stack(1)] + +- 2022-10-20 : 알고리즘[Stack(2)] + +- 2022-10-21 : 알고리즘[Stack(3)] + +- 2022-10-24 : 알고리즘[배열 자르고, 정렬, 찾기] + +- 2022-10-25 : 알고리즘[Hash] + +- 2022-10-26 : 알고리즘[Hash Collistion] + +- 2022-10-27 : 알고리즘[Hash(3)] - (프로그래머스) 완주하지 못한 선수 문제 + +- 2022-10-28 : 알고리즘[Hash(4)] - (프로그래머스) 폰켓몬, 전화번호 목록 + +- 2022-10-31 : 알고리즘[완전탐색] - (프로그래머스) 모의고사 + +- 2022-11-01 : 알고리즘[연습문제] - (프로그래머스) 소수찾기 + +- 2022-11-02 : 알고리즘[연습문제(2)] - (프로그래머스) 에라토스테네스의 체를 통한 소수찾기 + +- 2022-11-03 : 알고리즘[연습문제(2)] - (프로그래머스) 에라토스테네스의 체를 통한 소수찾기 완성 + +- 2022-11-07 : 알고리즘[PriorityQueue] - (프로그래머스) 하샤드 수 찾기, 나누어 떨어지는 숫자 배열 + +- 2022-11-08 : 알고리즘[이진탐색] - (코드업) 데이터탐색 + +- 2022-11-09 : 알고리즘[선택정렬] - 기본, interface(Strategy), BiFunction, BiPredicate 사용 + +- 2022-11-15 : 알고리즘[퀵정렬] - 재귀함수 사용 +
+ +# ⚙️ 기술 스택 +
+ Java + Mysql +
+ +
+ +## ☁️ 대용량데이터처리 프로젝트(1) +### ➀ 목적 +####    A지역에서 B지역으로 어느곳으로 이사를 많이 갔는지 횟수 구하기 + +### ➁ 진행 순서 +####    1. 대용량 데이터 파일을 다운받음 +####    2. 파일을 읽고 자신이 원하는 값만 추출함 +####    3. 현재 값이 숫자로 되어 있으므로 원하는 형식으로 맵핑함 +####    4. 추출한 데이터를 저장할 파일을 생성하고 파일에 데이터를 작성하여 저장함 + +### 📗 정리 블로그 +https://velog.io/@qowl880/Java-%EB%8C%80%EC%9A%A9%EB%9F%89%EC%B2%98%EB%A6%AC-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8 + + +
+ +## ☁️ 대용량데이터처리 프로젝트(2) +### ➀ 목적 +####    대용량데이터처리 프로젝트(1)에서 추출한 데이터를 Heat Map으로 출력하기 + +### ➁ 진행 순서 +####    1. 대용량 데이터 파일을 다운받음 +####    2. 파일을 읽고 자신이 원하는 값만 추출함 +####    3. 추출한 데이터를 저장할 파일을 생성하고 파일에 데이터를 작성하여 저장함 +####    4. 데이터를 가지고 Heat Map + +### 📗 정리 블로그 +https://velog.io/@qowl880/Java-%EB%8C%80%EC%9A%A9%EB%9F%89%EC%B2%98%EB%A6%AC-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B82-owien5hj + diff --git a/git/Lion-Java/src/Date10_06/CodeUp/No_1024.java b/git/Lion-Java/src/Date10_06/CodeUp/No_1024.java new file mode 100644 index 0000000..6a92d67 --- /dev/null +++ b/git/Lion-Java/src/Date10_06/CodeUp/No_1024.java @@ -0,0 +1,20 @@ +package Date10_06.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + + +public class No_1024 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + char[] str = new char[s.length()]; + + for(int i =0; i=0; i--){ + if(i!=0) + System.out.print(str[i]+"-"); + else + System.out.println(str[i]); + } + } +} diff --git a/git/Lion-Java/src/Date10_06/CodeUp/No_1028.java b/git/Lion-Java/src/Date10_06/CodeUp/No_1028.java new file mode 100644 index 0000000..636b030 --- /dev/null +++ b/git/Lion-Java/src/Date10_06/CodeUp/No_1028.java @@ -0,0 +1,16 @@ +package Date10_06.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1028 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + long num = Long.parseLong(s); + + System.out.println(num); + } +} diff --git a/git/Lion-Java/src/Date10_06/CodeUp/No_1029.java b/git/Lion-Java/src/Date10_06/CodeUp/No_1029.java new file mode 100644 index 0000000..057b926 --- /dev/null +++ b/git/Lion-Java/src/Date10_06/CodeUp/No_1029.java @@ -0,0 +1,17 @@ +package Date10_06.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1029 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + double num = Double.parseDouble(s); + + System.out.printf("%.11f",num); + } +} diff --git a/git/Lion-Java/src/Date10_06/CodeUp/No_1030.java b/git/Lion-Java/src/Date10_06/CodeUp/No_1030.java new file mode 100644 index 0000000..2018940 --- /dev/null +++ b/git/Lion-Java/src/Date10_06/CodeUp/No_1030.java @@ -0,0 +1,16 @@ +package Date10_06.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1030 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + long num = Long.parseLong(s); + System.out.println(s); + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1031.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1031.java new file mode 100644 index 0000000..7f04e1b --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1031.java @@ -0,0 +1,17 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1031 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + int num = Integer.parseInt(s); + + System.out.printf("%o",num); // %o 2진수로 출력 + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1032.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1032.java new file mode 100644 index 0000000..5c35601 --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1032.java @@ -0,0 +1,17 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1032 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + int num = Integer.parseInt(s); + + System.out.printf("%x",num); // 소문자 x는 16진수 소문자로 출력 + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1033.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1033.java new file mode 100644 index 0000000..e3f9708 --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1033.java @@ -0,0 +1,17 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1033 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + int num = Integer.parseInt(s); + + System.out.printf("%X",num); // 대문자 x는 16진수 대문자로 출력 + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1034.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1034.java new file mode 100644 index 0000000..cea8b41 --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1034.java @@ -0,0 +1,17 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1034 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + int num = Integer.parseInt(s,8); // 8진수로 저장한다는 뜻 + + System.out.printf("%d",num); + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1035.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1035.java new file mode 100644 index 0000000..410c2df --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1035.java @@ -0,0 +1,18 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1035 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + int num = Integer.parseInt(s,16); + + System.out.printf("%o",num); + + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1036.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1036.java new file mode 100644 index 0000000..14598e7 --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1036.java @@ -0,0 +1,19 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1036 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + char c = s.charAt(0); + + int num = c; + + System.out.println(num); + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1037.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1037.java new file mode 100644 index 0000000..3f9f3fd --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1037.java @@ -0,0 +1,19 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1037 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String s = bf.readLine(); + + int num = Integer.parseInt(s); + + char c = (char)num; + + System.out.println(c); + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1038.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1038.java new file mode 100644 index 0000000..3c03e23 --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1038.java @@ -0,0 +1,18 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1038 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = bf.readLine().split(" "); + + long num1 = Long.parseLong(str[0]); + long num2 = Long.parseLong(str[1]); + + System.out.println(num1 + num2); + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1039.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1039.java new file mode 100644 index 0000000..b7bc550 --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1039.java @@ -0,0 +1,18 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1039 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String[] s = bf.readLine().split(" "); + + long num1 = Long.parseLong(s[0]); + long num2 = Long.parseLong(s[1]); + + System.out.println(num1+num2); + } +} diff --git a/git/Lion-Java/src/Date10_07/CodeUp/No_1040.java b/git/Lion-Java/src/Date10_07/CodeUp/No_1040.java new file mode 100644 index 0000000..65896a6 --- /dev/null +++ b/git/Lion-Java/src/Date10_07/CodeUp/No_1040.java @@ -0,0 +1,15 @@ +package Date10_07.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1040 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + int num = Integer.parseInt(bf.readLine()); + + System.out.println(-(num)); + } +} diff --git a/git/Lion-Java/src/Date10_07/Project/PopulationMethod.java b/git/Lion-Java/src/Date10_07/Project/PopulationMethod.java new file mode 100644 index 0000000..7e0fb12 --- /dev/null +++ b/git/Lion-Java/src/Date10_07/Project/PopulationMethod.java @@ -0,0 +1,171 @@ +package Date10_07.Project; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; + +public class PopulationMethod { + static String address = "대용량 파일 위치"; + + static String saveaddress = "파싱,맵핑하여 추출한 데이터 저장할 파일 위치"; + static String heatsaveaddress = "HeatMap에 필요한 데이터 저장할 파일 "; + + public static void ReadByChar() throws IOException { // 1글자씩 읽기 + FileReader fileReader = new FileReader(address); + + String fileContents =""; + while(fileContents.length()<1_000_000) { + char c = (char) fileReader.read(); // read()는 반환을 int형으로 하기 때문에 형변환이 필요 + fileContents += c; + System.out.println(fileContents); + } + System.out.println(fileContents); + } + + public static String ReadByOneLine() throws IOException{ // 1줄 읽기 + BufferedReader reader = new BufferedReader( + new FileReader(address) + ); + String str = reader.readLine(); + reader.close(); + return str; + } + + public static void ReadByLine() throws IOException{ // 1줄씩 전부 읽기 + BufferedReader reader = new BufferedReader( + new FileReader(address) + ); + String str; + while ((str = reader.readLine()) != null) { + System.out.println(str); + } + reader.close(); + } + + public static void ReadByLine2() { // 1줄씩 전부 읽기 (2) + try (BufferedReader br = Files.newBufferedReader( + Paths.get(address), StandardCharsets.UTF_8)) { + String line; + while ((line = br.readLine()) != null) { + System.out.println(line); + } + } catch (IOException ex) { + throw new RuntimeException(ex); + } + } + + + public static PopulationMove parse(String data){ // 원하는 값 추출을 위한 파싱 + + String[] str = data.split(","); + int FromSido = Integer.parseInt(str[0]); // 11 + int ToSido = Integer.parseInt(str[6]); // 41 + + return new PopulationMove(FromSido,ToSido); // 맵핑한 값 반환 "서울,경기도" + } + + public static Map ReadByLineParse() throws IOException{ // 1줄씩 전부 읽어서 파싱하기 + Map mapcount = new HashMap<>(); // 카운트 저장할 Map + + BufferedReader reader = new BufferedReader( + new FileReader(address) + ); + String str; + while ((str = reader.readLine()) != null) { // 파일의 마지막 데이터까지 반복 + String pm = String.valueOf(parse(str)); // pm 참조변수에 parse,mapping한(한줄 읽기)값 저장 + + // 횟수 구하기 + if(mapcount.get(pm) == null) { // 처음 들어오는 값이면 1초기화 + mapcount.put(pm,1); + } + mapcount.put(pm,mapcount.get(pm)+1); // 2번째 부터 들어오는 값은 키,키값을 불러와 +1 + } + reader.close(); + + return mapcount; // 리스트 출력 + } + + public void CreateFile(){ // 파일 생성 + File file = new File(saveaddress); // 파일 생성 위치및 파일 이름 + try{ + System.out.println("파일 생성"); + file.createNewFile(); + }catch (IOException e){ + System.out.println("파일 생성 못함"); + throw new RuntimeException(); + } + } + + public void Filewrite(Mapstrs){ // 파일 작성 + File file = new File(saveaddress); + + try{ + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + + for(String str:strs.keySet()){ // 참조변수로 받은 리스트만큼 반복 + writer.write(str+","+strs.get(str)+"\n"); // 참조변수로 받은 리스트의 값+"\n" 으로 파일에 작성 + } + writer.close(); + }catch (IOException e){ + e.printStackTrace(); + } + } + + // -------------- heat를 위한 메서드 ---------------- + + public static String Heatparse(String data){ // heat에 넣기 위한 파싱 + String[] str = data.split(","); + String FromSido = str[0]; // 11 + String ToSido = str[6]; // 41 + String result = FromSido + ","+ToSido; + return result; + } + + public static Map HeatReadByLineParse() throws IOException{ // heat에 넣기 위한 1줄씩 전부 읽기 + Map mapcount = new TreeMap<>(); // 카운트 저장할 Map + + BufferedReader reader = new BufferedReader( + new FileReader(address) + ); + String str; + while ((str = reader.readLine()) != null) { // 파일의 마지막 데이터까지 반복 + String pm = Heatparse(str); // pm 참조변수에 parse,mapping한(한줄 읽기)값 저장 + + // 횟수 구하기 + if(mapcount.get(pm) == null) { // 처음 들어오는 값이면 1초기화 + mapcount.put(pm,1); + }else + mapcount.put(pm,mapcount.get(pm)+1); // 2번째 부터 들어오는 값은 키,키값을 불러와 +1 + } + reader.close(); + + return mapcount; // 리스트 출력 + } + + public void HeatCreateFile(){ // heat 파일 생성 + File file = new File(heatsaveaddress); // 파일 생성 위치및 파일 이름 + try{ + System.out.println("파일 생성"); + file.createNewFile(); + }catch (IOException e){ + System.out.println("파일 생성 못함"); + throw new RuntimeException(); + } + } + + public void HeatFilewrite(Mapstrs){ // heat 파일 작성 + File file = new File(heatsaveaddress); + + try{ + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + for(String str:strs.keySet()){ // 참조변수로 받은 리스트만큼 반복 + writer.write(str+","+strs.get(str)+"\n"); // 참조변수로 받은 리스트의 값+"\n" 으로 파일에 작성 + } + writer.close(); + }catch (IOException e){ + e.printStackTrace(); + } + } +} diff --git a/git/Lion-Java/src/Date10_07/Project/PopulationMove.java b/git/Lion-Java/src/Date10_07/Project/PopulationMove.java index de2caa0..4eba02b 100644 --- a/git/Lion-Java/src/Date10_07/Project/PopulationMove.java +++ b/git/Lion-Java/src/Date10_07/Project/PopulationMove.java @@ -5,10 +5,14 @@ 3. 이사하기 전 도시와 이사하고 난 후 도시의 값만 가져온다 */ +import java.util.HashMap; +import java.util.Map; + public class PopulationMove { private int fromSido; private int toSido; + int num; public PopulationMove(){ } @@ -26,8 +30,34 @@ public int getToSido() { return toSido; } + + public String Mapping(int num){ // 숫자입력시 해당하는 지역이름 반환 + + Map map = new HashMap<>(); + map.put(11,"서울"); + map.put(26,"부산"); + map.put(27,"대구"); + map.put(28,"인천"); + map.put(29,"광주"); + map.put(30,"대전"); + map.put(31,"울산"); + map.put(36,"세종"); + map.put(41,"경기도"); + map.put(42,"강원도"); + map.put(43,"충북"); + map.put(44,"충남"); + map.put(45,"전북"); + map.put(46,"전남"); + map.put(47,"경북"); + map.put(48,"경남"); + map.put(50,"제주"); + + return map.get(num); + } + @Override public String toString() { - return fromSido+"에서 "+toSido+"로 이사갔습니다."; + return Mapping(fromSido)+","+Mapping(toSido); } + } diff --git a/git/Lion-Java/src/Date10_07/Project/PopulationStatistics.java b/git/Lion-Java/src/Date10_07/Project/PopulationStatistics.java index 2e48637..38e09c9 100644 --- a/git/Lion-Java/src/Date10_07/Project/PopulationStatistics.java +++ b/git/Lion-Java/src/Date10_07/Project/PopulationStatistics.java @@ -1,77 +1,23 @@ package Date10_07.Project; - - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; - -public class PopulationStatistics { - - static String address = "C:\\Users\\qowhx\\OneDrive\\바탕 화면\\인구\\2021_인구관련연간자료_20221006_47106.csv"; - - - public static void ReadByChar() throws IOException{ // 1글자씩 읽기 - FileReader fileReader = new FileReader(address); - - String fileContents =""; - while(fileContents.length()<1_000_000) { - char c = (char) fileReader.read(); // read()는 반환을 int형으로 하기 때문에 형변환이 필요 - fileContents += c; - System.out.println(fileContents); - } - System.out.println(fileContents); - } - public static String ReadByOneLine() throws IOException{ // 1줄 읽기 - BufferedReader reader = new BufferedReader( - new FileReader(address) - ); - String str = reader.readLine(); - reader.close(); - return str; - } - - public static void ReadByLine() throws IOException{ // 1줄씩 전부 읽기 - BufferedReader reader = new BufferedReader( - new FileReader(address) - ); - String str; - while ((str = reader.readLine()) != null) { - System.out.println(str); - } - reader.close(); - } - - public static void ReadByLine2() { // 1줄씩 전부 읽기 (2) - try (BufferedReader br = Files.newBufferedReader( - Paths.get(address), StandardCharsets.UTF_8)) { - String line; - while ((line = br.readLine()) != null) { - System.out.println(line); - } - } catch (IOException ex) { - throw new RuntimeException(ex); - } - } - - public static PopulationMove parse(String data) throws IOException { - String[] str = data.split(","); - int FromSido = Integer.parseInt(str[0]); - int ToSido = Integer.parseInt(str[6]); - - return new PopulationMove(FromSido,ToSido); - } +public class PopulationStatistics { public static void main(String[] args) throws IOException { - // ReadByChar(); - // ReadByLine(); - // ReadByLine2(); - System.out.println(parse(ReadByOneLine())); + PopulationMethod method = new PopulationMethod(); + // method.ReadByChar(); // 파일 한글자씩 읽기 + // method.ReadByLine(); // 파일 한줄씩 읽기 + // method.ReadByLine2(); // 파일 한줄씩 읽기(2) + // System.out.println(method.parse(method.ReadByOneLine())); // 파일 한줄만 읽어서 파싱 후 한글로 Mapping + // System.out.println(method.ReadByLineParse()); + + method.CreateFile(); + method.Filewrite(method.ReadByLineParse()); // 파싱한 값 맵핑하여 파일에 저장 + + // heat 차트 작성을 위한 작업 + method.HeatCreateFile(); + method.HeatFilewrite(method.HeatReadByLineParse()); + } } diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1041.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1041.java new file mode 100644 index 0000000..f798936 --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1041.java @@ -0,0 +1,17 @@ +package Date10_11.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1041 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + char c = bf.readLine().charAt(0); + + int num = (int)c; + + System.out.println((char)(num+1)); + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1042.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1042.java new file mode 100644 index 0000000..70b0800 --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1042.java @@ -0,0 +1,18 @@ +package Date10_11.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1042 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = bf.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + System.out.println(num1/num2); + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1043.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1043.java new file mode 100644 index 0000000..efa397a --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1043.java @@ -0,0 +1,16 @@ +package Date10_11.Algorithm.CodeUp; + +import java.util.Scanner; + +public class No_1043 { + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); + + String[] str = scan.nextLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + System.out.println(num1 % num2); + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1044.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1044.java new file mode 100644 index 0000000..a121d4d --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1044.java @@ -0,0 +1,13 @@ +package Date10_11.Algorithm.CodeUp; + +import java.util.Scanner; + +public class No_1044 { + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); + + long num =scan.nextInt(); + + System.out.println(num+1); + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1045.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1045.java new file mode 100644 index 0000000..cb36354 --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1045.java @@ -0,0 +1,23 @@ +package Date10_11.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1045 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = bf.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + System.out.println(num1 + num2); + System.out.println(num1 - num2); + System.out.println(num1 * num2); + System.out.println(num1 / num2); + System.out.println(num1 % num2); + System.out.printf("%.2f",(float)num1/(float)num2); + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1046.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1046.java new file mode 100644 index 0000000..489af11 --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1046.java @@ -0,0 +1,19 @@ +package Date10_11.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1046 { + public static void main(String[] args) throws IOException { + BufferedReader bf =new BufferedReader(new InputStreamReader(System.in)); + + String[] str = bf.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + int num3 = Integer.parseInt(str[2]); + System.out.println(num1+num2+num3); + System.out.printf("%.1f",(float)((num1+num2+num3))/str.length); + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1047.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1047.java new file mode 100644 index 0000000..67f6878 --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1047.java @@ -0,0 +1,20 @@ +package Date10_11.Algorithm.CodeUp; + +import java.util.Scanner; + +public class No_1047 { + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); + + int num = scan.nextInt(); + + System.out.println(num<<1); + + // 비트 단위 시프트 연산자 + // ex. int a = 10; + // printf("%d", a<<1); //10을 2배 한 값인 20 이 출력된다. + // printf("%d", a>>1); //10을 반으로 나눈 값인 5 가 출력된다. + // printf("%d", a<<2); //10을 4배 한 값인 40 이 출력된다. + // printf("%d", a>>2); //10을 반으로 나눈 후 다시 반으로 나눈 값인 2 가 출력된다. + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1048.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1048.java new file mode 100644 index 0000000..e54ab40 --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp/No_1048.java @@ -0,0 +1,18 @@ +package Date10_11.Algorithm.CodeUp; + +import java.util.Scanner; + +public class No_1048 { + public static void main(String[] args) { + Scanner scan = new Scanner(System.in); + + String[] str = scan.nextLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + System.out.println(num1<0){ + num /= 10; + count ++; + } + + System.out.println(count); + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/CodeUp_1620.java b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp_1620.java new file mode 100644 index 0000000..06e4be3 --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/CodeUp_1620.java @@ -0,0 +1,22 @@ +package Date10_11.Algorithm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class CodeUp_1620 { + public static void main(String[] args) throws IOException { + BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); + + int num = Integer.parseInt(bf.readLine()); + int result = 0; + + + while(num>0){ + result += num%10; + num /= 10; + } + + System.out.println(result); + } +} diff --git a/git/Lion-Java/src/Date10_11/Algorithm/Solution.java b/git/Lion-Java/src/Date10_11/Algorithm/Solution.java new file mode 100644 index 0000000..3776b82 --- /dev/null +++ b/git/Lion-Java/src/Date10_11/Algorithm/Solution.java @@ -0,0 +1,14 @@ +package Date10_11.Algorithm; + +public class Solution { + public int solution(int n){ + int result = 0; + + while(n>0){ + result += n%10; + + result /= 10; + } + return result; + } +} diff --git a/git/Lion-Java/src/Date10_12/LineReader.java b/git/Lion-Java/src/Date10_12/LineReader.java new file mode 100644 index 0000000..a700631 --- /dev/null +++ b/git/Lion-Java/src/Date10_12/LineReader.java @@ -0,0 +1,37 @@ +package Date10_12; + +import Date10_12.pasrser.Parser; + +import java.io.BufferedReader; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class LineReader { + Parser parser; + boolean isRemoveColumnName = true; + + public LineReader(Parser parser) { + this.parser = parser; + } + + public LineReader(Parser parser, boolean isRemoveColumnName) { + this.parser = parser; + this.isRemoveColumnName = isRemoveColumnName; + } + + List readLines(String filename) throws IOException { + List result = new ArrayList<>(); + BufferedReader br = new BufferedReader(new FileReader(filename)); + String str; + if (isRemoveColumnName) { + br.readLine(); + } + while ((str = br.readLine()) != null) { + result.add(parser.parse(str)); + } + return result; + } + +} diff --git a/git/Lion-Java/src/Date10_12/Main.java b/git/Lion-Java/src/Date10_12/Main.java new file mode 100644 index 0000000..8686eb6 --- /dev/null +++ b/git/Lion-Java/src/Date10_12/Main.java @@ -0,0 +1,20 @@ +package Date10_12; + +import Date10_12.domain.Hospital; +import Date10_12.pasrser.HospitalParser; + +import java.io.IOException; +import java.util.List; + +public class Main { + public static void main(String[] args) throws IOException { + LineReader hospitalLineReader = new LineReader<>(new HospitalParser()); + String filename = "C:\\Users\\ocean\\Downloads\\서울시 병의원 위치 정보.csv"; + List hospitals = hospitalLineReader.readLines(filename); + + System.out.println(hospitals.size()); + for (Hospital hospital : hospitals) { + System.out.println(hospital.getId()); + } + } +} diff --git a/git/Lion-Java/src/Date10_12/domain/Hospital.java b/git/Lion-Java/src/Date10_12/domain/Hospital.java new file mode 100644 index 0000000..a7b2a0a --- /dev/null +++ b/git/Lion-Java/src/Date10_12/domain/Hospital.java @@ -0,0 +1,19 @@ +package Date10_12.domain; + +public class Hospital { + private String id; + private String address; + private String district; + private String category; + private Integer emergencyRoom; // snake camel + private String name; // snake camel + private String subdivision; // snake camel + + public Hospital(String id) { + this.id = id; + } + + public String getId() { + return id; + } +} \ No newline at end of file diff --git a/git/Lion-Java/src/Date10_12/pasrser/HospitalParser.java b/git/Lion-Java/src/Date10_12/pasrser/HospitalParser.java new file mode 100644 index 0000000..af78724 --- /dev/null +++ b/git/Lion-Java/src/Date10_12/pasrser/HospitalParser.java @@ -0,0 +1,11 @@ +package Date10_12.pasrser; + +import Date10_12.domain.Hospital; + +public class HospitalParser implements Parser{ + @Override + public Hospital parse(String str) { + String[] splitted = str.split(","); + return new Hospital(splitted[0]); + } +} diff --git a/git/Lion-Java/src/Date10_12/pasrser/Parser.java b/git/Lion-Java/src/Date10_12/pasrser/Parser.java new file mode 100644 index 0000000..ee5a7e8 --- /dev/null +++ b/git/Lion-Java/src/Date10_12/pasrser/Parser.java @@ -0,0 +1,5 @@ +package Date10_12.pasrser; + +public interface Parser { + T parse(String str); +} \ No newline at end of file diff --git a/git/Lion-Java/src/Date10_13/Algorithm/BubbleSort.java b/git/Lion-Java/src/Date10_13/Algorithm/BubbleSort.java new file mode 100644 index 0000000..0b05e10 --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/BubbleSort.java @@ -0,0 +1,35 @@ +package Date10_13.Algorithm; + + +/* 버블정렬 + (1) swap 자리 바꾸기 + (2) 이중 for문 + (3) 이중 for문 control + +*/ + +import java.util.Arrays; +public class BubbleSort { + + public int[] sort(int[] arr){ + for(int i=1; i arr[j+1]) { + int temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + } + } + System.out.println(Arrays.toString(arr)); + } + return arr; + } + + public static void main(String[] args) { + int[] arr = {7,2,3,9,28,11}; + BubbleSort b = new BubbleSort(); + int[] result = b.sort(arr); + + System.out.println(Arrays.toString(result)); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1050.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1050.java new file mode 100644 index 0000000..cc835e6 --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1050.java @@ -0,0 +1,21 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1050 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + if(num1 == num2) + System.out.println("1"); + else + System.out.println("0"); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1051.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1051.java new file mode 100644 index 0000000..db52b29 --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1051.java @@ -0,0 +1,21 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1051 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + if(num1 <= num2) + System.out.println("1"); + else + System.out.println("0"); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1052.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1052.java new file mode 100644 index 0000000..db47b10 --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1052.java @@ -0,0 +1,21 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1052 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + if(num1 != num2) + System.out.println("1"); + else + System.out.println("0"); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1053.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1053.java new file mode 100644 index 0000000..5b07245 --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1053.java @@ -0,0 +1,18 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1053 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + int num1 = Integer.parseInt(br.readLine()); + + if(num1 == 1) + System.out.println("0"); + else + System.out.println("1"); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1054.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1054.java new file mode 100644 index 0000000..f176509 --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1054.java @@ -0,0 +1,21 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1054 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + if(num1 ==1 && num2 == 1) + System.out.println("1"); + else + System.out.println("0"); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1055.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1055.java new file mode 100644 index 0000000..82407c8 --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1055.java @@ -0,0 +1,21 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1055 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + if(num1 ==1 || num2 == 1) + System.out.println("1"); + else + System.out.println("0"); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1056.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1056.java new file mode 100644 index 0000000..d1bb74d --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1056.java @@ -0,0 +1,21 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1056 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + if((num1 ==1 && num2 != 1)||(num1 !=1 && num2 == 1)) + System.out.println("1"); + else + System.out.println("0"); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1057.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1057.java new file mode 100644 index 0000000..b7121fa --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1057.java @@ -0,0 +1,21 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1057 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + if(num1 == num2) + System.out.println("1"); + else + System.out.println("0"); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1058.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1058.java new file mode 100644 index 0000000..0ca640c --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1058.java @@ -0,0 +1,17 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1058 { + public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + boolean num1 = Integer.parseInt(str[0]) != 0; + boolean num2 = Integer.parseInt(str[1]) != 0; + + System.out.print(num1||num2? 0:1); + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1059.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1059.java new file mode 100644 index 0000000..f45bf2f --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1059.java @@ -0,0 +1,17 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1059 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + int num = Integer.parseInt(br.readLine()); + + System.out.printf("%d",~num); // 비트단위논리연산 + // ~n = -n -1 + // ex) 2일때 ~2 = -2 -1 + } +} diff --git a/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1060.java b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1060.java new file mode 100644 index 0000000..42de7e8 --- /dev/null +++ b/git/Lion-Java/src/Date10_13/Algorithm/CodeUp/No_1060.java @@ -0,0 +1,23 @@ +package Date10_13.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1060 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + String[] str = br.readLine().split(" "); + + int num1 = Integer.parseInt(str[0]); + int num2 = Integer.parseInt(str[1]); + + System.out.printf("%d",num1&num2); // 비트단위 연산자 + // 두개의 값의 비트연산자를 더함(중복 자리의 값만 1로 반환) + // ex) + // 3 : 00000000 00000000 00000000 00000011 + // 5 : 00000000 00000000 00000000 00000101 + // 3 & 5 : 00000000 00000000 00000000 00000001 + } +} diff --git a/git/Lion-Java/src/Date10_14/Algorithm/CodeUp/No_1443.java b/git/Lion-Java/src/Date10_14/Algorithm/CodeUp/No_1443.java new file mode 100644 index 0000000..bc0fceb --- /dev/null +++ b/git/Lion-Java/src/Date10_14/Algorithm/CodeUp/No_1443.java @@ -0,0 +1,32 @@ +package Date10_14.Algorithm.CodeUp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class No_1443 { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + int num = Integer.parseInt(br.readLine()); // 배열 사이즈 입력 + int[] arr = new int[num]; + + for(int i = 0; i=0; j--){ + if(arr[j] < arr[j+1]){ + int tmp = arr[j+1]; + arr[j+1] = arr[j]; + arr[j] = tmp; + } + } + } + + for(int i= num-1; i>=0; i--){ + System.out.println(arr[i]); + } + } +} diff --git a/git/Lion-Java/src/Date10_14/Algorithm/InsertSort.java b/git/Lion-Java/src/Date10_14/Algorithm/InsertSort.java new file mode 100644 index 0000000..365178f --- /dev/null +++ b/git/Lion-Java/src/Date10_14/Algorithm/InsertSort.java @@ -0,0 +1,31 @@ +package Date10_14.Algorithm; + +// 삽입정렬 + +import java.util.Arrays; + +public class InsertSort { + + static int[] sort(int[] arr){ + + for(int i=1; i= 0; j--) { // 이전 값 모두 비교(이전값 개수만큼 반복) + if (arr[j+1] < arr[j]) { + int tmp = arr[j+1]; + arr[j+1] = arr[j]; + arr[j] = tmp; + } + System.out.println(Arrays.toString(arr)); + } + } + return arr; + } + + + public static void main(String[] args) { + int[] arr = {8,5,6,2,4}; + + System.out.println(Arrays.toString(sort(arr))); + } +} + diff --git a/git/Lion-Java/src/Date10_17/Algorithm/Diamond.java b/git/Lion-Java/src/Date10_17/Algorithm/Diamond.java new file mode 100644 index 0000000..0ff0ae9 --- /dev/null +++ b/git/Lion-Java/src/Date10_17/Algorithm/Diamond.java @@ -0,0 +1,36 @@ +package Date10_17.Algorithm; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; + +public class Diamond { + public static void main(String[] args) throws IOException { + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); + + int num = Integer.parseInt(br.readLine()); + + input(num); + } + + static void input(int num){ + for(int i=0; i=0; i--){ + for(int j=1; j