📢 오늘의 목표 📢
✔️ 알고리즘, SQL 문제 풀이
✔️ 알고리즘 코드카타
✔️ SQL 코드카타
✔️ 프로그래머스 Level 1
✔️ 점프 투 스프링 부트
✔️ 2장
✔️ 개인 과제 보강
⏱️ 오늘의 일정 ⏱️
9:00 ~ 10:00 - 알고리즘, SQL 문제 풀이
10:00 ~ 10:30 - 3주 차 발제
10:30 ~ 12:30 - 알고리즘 문제 풀이
12:30 ~ 14:00 - 점심시간
14:00 ~ 16:00 - 개인 과제 보강
16:00 ~ 18:00 - 스프링 공부 (점프 투 스프링 부트)
18:00 ~ 19:00 - 저녁 시간
19:00 ~ 20:00 - 스프링 공부 (점프 투 스프링 부트)
20:00 ~ 21:00 - TIL 작성
📜 Chapter 1. 알고리즘, SQL 문제 풀이
9:00 ~ 10:00 - 알고리즘, SQL 문제 풀이
10:30 ~ 12:30 - 알고리즘 문제 풀이
✔️ 알고리즘, SQL 문제 풀이
✔️ 알고리즘 코드카타
✔️ SQL 코드카타
✔️ 프로그래머스 Level 1
✔️ 알고리즘 코드카타
두 수의 합
class Solution {
public int solution(int num1, int num2) {
int answer = -1;
answer = num1 + num2;
return answer;
}
}
CodingTest_AutoSave/프로그래머스/0/120802. 두 수의 합 at main · MetroDefro/CodingTest_AutoSave
모든 코딩 테스트 자동 저장. Contribute to MetroDefro/CodingTest_AutoSave development by creating an account on GitHub.
github.com
두 수의 나눗셈
class Solution {
public int solution(int num1, int num2) {
int answer = 0;
answer = (int)(num1 / (double)num2 * 1000);
return answer;
}
}
CodingTest_AutoSave/프로그래머스/0/120806. 두 수의 나눗셈 at main · MetroDefro/CodingTest_AutoSave
모든 코딩 테스트 자동 저장. Contribute to MetroDefro/CodingTest_AutoSave development by creating an account on GitHub.
github.com
각도기
class Solution {
public int solution(int angle) {
int answer = 0;
if(0 < angle && angle < 90)
answer = 1;
else if(angle == 90)
answer = 2;
else if(90 < angle && angle < 180)
answer = 3;
else if(angle == 180)
answer = 4;
return answer;
}
}
CodingTest_AutoSave/프로그래머스/0/120829. 각도기 at main · MetroDefro/CodingTest_AutoSave
모든 코딩 테스트 자동 저장. Contribute to MetroDefro/CodingTest_AutoSave development by creating an account on GitHub.
github.com
✔️ SQL 코드카타
동명 동물 수 찾기
SELECT NAME, COUNT(NAME) as COUNT
FROM ANIMAL_INS
GROUP BY NAME
HAVING COUNT(NAME) >= 2
ORDER BY 1
CodingTest_AutoSave/프로그래머스/2/59041. 동명 동물 수 찾기 at main · MetroDefro/CodingTest_AutoSave
모든 코딩 테스트 자동 저장. Contribute to MetroDefro/CodingTest_AutoSave development by creating an account on GitHub.
github.com
아픈 동물 찾기
SELECT ANIMAL_ID, NAME
FROM ANIMAL_INS
WHERE INTAKE_CONDITION = "Sick"
ORDER BY 1
CodingTest_AutoSave/프로그래머스/1/59036. 아픈 동물 찾기 at main · MetroDefro/CodingTest_AutoSave
모든 코딩 테스트 자동 저장. Contribute to MetroDefro/CodingTest_AutoSave development by creating an account on GitHub.
github.com
상위 n개 레코드
SELECT NAME
FROM ANIMAL_INS
WHERE DATETIME =
(
SELECT MIN(DATETIME)
FROM ANIMAL_INS
)
CodingTest_AutoSave/프로그래머스/1/59405. 상위 n개 레코드 at main · MetroDefro/CodingTest_AutoSave
모든 코딩 테스트 자동 저장. Contribute to MetroDefro/CodingTest_AutoSave development by creating an account on GitHub.
github.com
✔️ 프로그래머스 Level 1
import java.util.Arrays;
import java.util.Comparator;
class Solution {
public int[][] solution(int[][] data, String ext, int val_ext, String sort_by) {
int[][] answer = {};
int standardExt = parse_index(ext);
int standardSort = parse_index(sort_by);
int[][] extData = Arrays.stream(data).filter(x -> x[standardExt] < val_ext).toArray(int[][]::new);
Arrays.sort(extData, Comparator.comparingInt(o -> o[standardSort]));
answer = extData;
return answer;
}
public int parse_index(String standard){
int index = 0;
switch (standard) { // 뽑아낼 데이터 기준
case "code": // 제일 왼쪽 열일 경우부터 순서대로
index = 0; // 열의 인덱스를 저장
break;
case "date":
index = 1;
break;
case "maximum":
index = 2;
break;
case "remain":
index = 3;
break;
}
return index;
}
}
CodingTest_AutoSave/프로그래머스/1/250121. [PCCE 기출문제] 10번 / 데이터 분석 at main · Metro
모든 코딩 테스트 자동 저장. Contribute to MetroDefro/CodingTest_AutoSave development by creating an account on GitHub.
github.com
귀찮아서 (피곤해서) 따로 설명은 안 적었다...
어떻게 풀어야 할지는 바로 눈에 들어왔어서 이왕 하는 거 퀵 소트 만들어서 써보려 했는데
잘 되지도 않고 안 그래도 피곤하니 머리도 안 돌아가고
거의 한 시간 끙끙 앓다가 이번엔 Arrays.sort 기능을 이용하고 정렬에 대해서는 다음에 더 공부해 보기로 했다.
그런데 아직도 왜... 자꾸 틀리는지... 이해도 안 되고 아무리 코드를 봐도 틀린 것 같은 구석이 없었다.
그렇게 또 삽질을 하다가
오타를 조심하자 진짜...
똑똑한 인텔리제이는 이상하다고 생각하면 밑줄도 쳐준다.
저거 없었으면 푸는 데 몇 시간은 더 걸렸을지도 모른다 ㅋㅋㅋㅋㅋㅋ
📜 Chapter 2. 개인 과제
14:00 ~ 16:00 - 개인 과제 보강
✔️ 개인 과제 보강
public class App {
public static void main(String[] args) {
// 사칙연산, 원 넓이 계산기 각각 생성
ArithmeticCalculator arithmeticCalculator = new ArithmeticCalculator();
CircleCalculator circleCalculator = new CircleCalculator();
Scanner sc = new Scanner(System.in); // 스캐너 생성
boolean isEnd = false; // 종료 할지 여부를 boolean에 저장하기 위해 변수 생성.
do { // 첫번째는 무조건 실행.
System.out.println("계산기 옵션(번호 입력): 1. 사칙연산, 2. 원의 너비 구하기"); // 사칙연산 원의 너비 중 선택하도록 제시
try {
switch (Calculator.parseInputToOption(sc.nextLine(), 2)) {
case 1: // 사칙 연산 로직
// double, int 중 선택하도록 제시
System.out.print("계산 할 타입을 선택해주세요(번호 입력): 1. 정수, 2. 실수 ");
int type = Calculator.parseInputToOption(sc.nextLine(), 2); // 무슨 타입인지 받는다
double result = 0; // result를 if 문 밖으로 뺐다.
if (type == 1) { // 정수 선택
System.out.print("첫 번째 숫자를 입력하세요: ");
int firstNumber = Calculator.parseInputToInt(sc.nextLine()); // int를 입력받아 파싱.
System.out.print("두 번째 숫자를 입력하세요: ");
int secondNumber = Calculator.parseInputToInt(sc.nextLine()); // int를 입력받아 파싱.
System.out.print("사칙연산 기호를 입력하세요: ");
char operator = sc.nextLine().charAt(0); // 입력 받은 string의 인덱스 0번 char을 가져온다.
result = arithmeticCalculator.calculate(firstNumber, secondNumber, operator);
} else if (type == 2) { // 실수 선택
System.out.print("첫 번째 숫자를 입력하세요: ");
double firstNumber = Calculator.parseInputToDouble(sc.nextLine()); // double 입력 받는다.
System.out.print("두 번째 숫자를 입력하세요: ");
double secondNumber = Calculator.parseInputToDouble(sc.nextLine()); // double 입력 받는다.
System.out.print("사칙연산 기호를 입력하세요: ");
char operator = sc.nextLine().charAt(0); // 입력 받은 string의 인덱스 0번 char을 가져온다.
result = arithmeticCalculator.calculate(firstNumber, secondNumber, operator);
}
System.out.println("결과: " + result);
arithmeticCalculator.getResults().add(result); // 리스트에 결과 추가
System.out.println("가장 먼저 저장된 연산 결과를 삭제하시겠습니까? (remove 입력 시 삭제)");
if (sc.nextLine().equals("remove")) { // 입력 받은 답변이 "remove"일 경우
arithmeticCalculator.removeResult(); // 첫 결과 삭제
}
System.out.println("저장된 연산결과를 조회하시겠습니까? (inquiry 입력 시 조회)");
if (sc.nextLine().equals("inquiry")) { // 입력 받은 답변이 "inquiry"일 경우
arithmeticCalculator.inquiryResults(); // 결과 조회
}
System.out.println("입력 값보다 더 큰 값을 조회하겠습니다. 기준 숫자를 입력하세요.");
double standardNumber = Calculator.parseInputToDouble(sc.nextLine()); // double 입력 받는다.
arithmeticCalculator.inquiryBigger(standardNumber); // 결과 조회
System.out.println("더 계산하시겠습니까? (exit 입력 시 종료)");
isEnd = sc.nextLine().equals("exit"); // 입력 받은 답변이 "exit"라면 isEnd는 true 아니면 false 유지
break;
case 2: // 원의 너비 구하기 로직
System.out.print("원의 반지름을 입력하세요: ");
int radius = Calculator.parseInputToInt(sc.nextLine()); // int를 입력 받는다.
result = circleCalculator.calculate(radius); // 원 넓이 구하는 메서드 호출하고 값 result에 저장
System.out.println("결과: " + result);
circleCalculator.getResults().add(result); // 컬렉션에 결과 저장
circleCalculator.inquiryResults(); // 원의 넓기 결과들 바로 전체 조회
System.out.println("더 계산하시겠습니까? (exit 입력 시 종료)");
isEnd = sc.nextLine().equals("exit"); // 입력 받은 답변이 "exit"라면 isEnd는 true 아니면 false 유지
break;
}
} catch (InputErrorException e) {
System.out.println(e.getMessage());
}
} while (!isEnd);
}
}
import java.util.LinkedList;
public abstract class Calculator {
// ...
// 파싱하는 부분은 인스턴스 별로 있을 이유가 없어서 static으로 만들었다.
public static int parseInputToOption(String input, int optionCount) throws InputErrorException { // int 파싱
// 옵션 수 보다 많은 값 of 0이하 값 입력
int result = parseInputToInt(input);
if(result <= 0 || result > optionCount) { // 정규식 검사
throw new InputErrorException("옵션에 해당하는 값을 입력해주세요."); // exception 만들어 던짐
}
return result;
}
public static int parseInputToInt(String input) throws InputErrorException { // int 파싱
// 양수가 들어오지 않을 경우 예외처리
if(input.matches("^[0-9]+$")) { // 정규식 검사
return Integer.parseInt(input);
} else {
throw new InputErrorException("0을 포함한 양의 정수를 입력해야 합니다."); // exception 만들어 던짐
}
}
public static double parseInputToDouble(String input) throws InputErrorException { // double 파싱
// 양수가 들어오지 않을 경우 예외처리
if(input.matches("^[^0]\\d*|^[^0]\\d*\\.{1}\\d*[^0]$|^(0.)\\d*[^0]$")) {
return Double.parseDouble(input);
} else {
throw new InputErrorException("0을 포함한 양의 실수를 입력해야 합니다."); // exception 만들어 던짐
}
}
}
과제는 저번 금요일에 마쳤으나 예외 처리를 보강하고 싶었다.
그래서 Calculator에 static으로 파싱하는 메서드를 뒀다.
과제 제출도 마쳤고 github 링크는 아래에 있다.
https://github.com/MetroDefro/java_personal_project
GitHub - MetroDefro/java_personal_project: 내일배움캠프 자바 개인 과제
내일배움캠프 자바 개인 과제. Contribute to MetroDefro/java_personal_project development by creating an account on GitHub.
github.com
📜 Chapter 3. 스프링 찍먹
16:00 ~ 18:00 - 스프링 공부 (점프 투 스프링 부트)
19:00 ~ 20:00 - 스프링 공부 (점프 투 스프링 부트)
✔️ 점프 투 스프링 부트
✔️ 2장
정식 스프링 주차 시작 전 워밍업 한다는 느낌으로 계속 스프링 찍먹이라는 부제를 사용하기로 했다.
Query did not return a unique result: n results were returned 에러
findBySubject 메서드 부분 실습을 진행하는데 자꾸 에러가 뜬다.
이유는 저번에 했던 삽질 때문이다.
예제에서는 같은 데이터가 하나씩만 담겼을 텐데 나는 실수로 12개나........만들어버렸다.
public interface QuestionRepository extends JpaRepository<Question, Integer> {
List<Question> findBySubject(String subject);
}
@SpringBootTest
class JumpToSpringBootApplicationTests {
@Autowired
private QuestionRepository questionRepository;
@Test
void testJpa() {
List<Question> q = this.questionRepository.findBySubject("sbb가 무엇인가요?");
assertEquals(1, q.get(0).getId());
}
}
대신 List를 사용해 모든 결과값을 가져올 수 있게 만들면 해결.
메서드 구현을 하지 않았는데 실행될 수 있는 이유는 JPA에서 메서드명을 분석해(findBy + 엔티티의 속성명) 쿼리를 만들고 실행하는 기능이 있기 때문이다.
SQL 연산자 | 리포지터리의 메서드 | 예시설명 |
And | findBySubjectAndContent(String subject, String content) | Subject, Content 열과 일치하는 데이터를 조회 |
Or | findBySubjectOrContent(String subject, String content) | Subject열 또는 Content 열과 일치하는 데이터를 조회 |
Between | findByCreateDateBetween(LocalDateTime fromDate, LocalDateTime toDate) | CreateDate 열의 데이터 중 정해진 범위 내에 있는 데이터를 조회 |
LessThan | findByIdLessThan(Integer id) | Id 열에서 조건보다 작은 데이터를 조회 |
GreaterThanEqual | findByIdGreaterThanEqual(Integer id) | Id 열에서 조건보다 크거나 같은 데이터를 조회 |
Like | findBySubjectLike(String subject) | Subject 열에서 문자열 ‘subject’와 같은 문자열을 포함한 데이터를 조회 |
In | findBySubjectIn(String[] subjects) | Subject 열의 데이터가 주어진 배열에 포함되는 데이터만 조회 |
OrderBy | findBySubjectOrderByCreateDateAsc(String subject) | Subject 열 중 조건에 일치하는 데이터를 조회하여 CreateDate 열을 오름차순으로 정렬하여 반환 |
쿼리 생성 규칙을 담은 스프링 공식 문서
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
Spring Data JPA :: Spring Data JPA
Oliver Gierke, Thomas Darimont, Christoph Strobl, Mark Paluch, Jay Bryant, Greg Turnquist Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that
docs.spring.io
키워드: 템플릿 엔진
템플릿은 자바코드를 삽입할 수 있는 HTML 형식의 파일
템플릿 엔진에는 Thymeleaf, Mustache, Groovy, Freemarker, Velocity 등이 있다.
Thymeleaf
Integrations galore Eclipse, IntelliJ IDEA, Spring, Play, even the up-and-coming Model-View-Controller API for Java EE 8. Write Thymeleaf in your favourite tools, using your favourite web-development framework. Check out our Ecosystem to see more integrati
www.thymeleaf.org
키워드: Model
QuestionRepository로 조회한 질문 목록 데이터는 Model 클래스를 사용하여 템플릿에 전달할 수 있다.
Model 객체에 값을 담아 두면 템플릿에서 그 값을 사용할 수 있다. Model 객체는 따로 생성할 필요 없이 컨트롤러의 메서드에 매개변수로 지정하기만 하면 스프링 부트가 자동으로 Model 객체를 생성한다.
키워드: @RequiredArgsConstructor
@RequiredArgsConstructor 애너테이션의 생성자 방식으로 questionRepository 객체를 주입
키워드: th:each="question : ${questionList}"
🌙 오늘을 마치며 🌙
개발을 하다 보면 이상한 곳에서 한 사소한 실수로 몇 시간, 한 나절을 날려버리는 경우가 왕왕 있다.
처음엔 이럴 때마다 시간 낭비 했다는 생각에 힘들었는데 점점 어쨌든 해결했으니 됐음!!!이라는 마음가짐으로 살게 되는 것 같다.
오늘은 저번 주 금요일보다 더 피곤하다... 저번에는 피곤하기만 했다면 오늘은 완전 몸살이 나 버렸다.
그런 탓에 12시간을 제대로 집중하지 못했다...
그래도 할 수 있는 최선을 다했다고 생각한다.
아무튼 고생했다!
'공부 기록 > 내배캠Java_5기' 카테고리의 다른 글
[내배캠][TIL] 14일 차 - 목요일, 팀 프로젝트 시작 (1) | 2024.05.02 |
---|---|
[내배캠][TIL] 12일 차 - 화요일, 빡세게 공부한 날 (1) | 2024.04.30 |
[내배캠][TIL] 10일 차 - 금요일, 스프링 찍먹 (1) | 2024.04.26 |
[내배캠][TIL] 9일 차 - 목요일, 알고리즘 문제 풀이 시작과 개인 과제 (1) | 2024.04.25 |
[내배캠][TIL] 8일 차 - 수요일, 자바 강의 끝! (1) | 2024.04.24 |