Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2주차 Assignment - 정다연 #9

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions dayeon/advanced-java-assignment/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
### IntelliJ IDEA ###
out/
!**/src/main/**/out/
!**/src/test/**/out/

### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
bin/
!**/src/main/**/bin/
!**/src/test/**/bin/

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/

### VS Code ###
.vscode/

### Mac OS ###
.DS_Store
8 changes: 8 additions & 0 deletions dayeon/advanced-java-assignment/.idea/.gitignore

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions dayeon/advanced-java-assignment/.idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions dayeon/advanced-java-assignment/.idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions dayeon/advanced-java-assignment/advanced-java-assignment.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
22 changes: 22 additions & 0 deletions dayeon/advanced-java-assignment/src/T1/Test1.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package T1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.NoSuchElementException;

public class Test1 {

public static List<Integer> list = new ArrayList<>();

public static void main(String[] args) {
list = Arrays.asList(1, 2, 3 ,4, 5 ,6);

double avg = list.stream()
.mapToDouble(Math::sqrt)
.average()
.orElseThrow(NoSuchElementException::new);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

잘 작성하셨습니다!!
궁금한 점이기는 한데 혹시 어쩌다 저렇게 들여쓰기가 되었나요..?ㅋㅋㅋ

왜 스트림에서 double을 반환할 때 orElseThrow를 통해 예외 처리를 해야할까요?
사실 averge() 메소드가 반환하는 값은 double 타입이 아니라 Optional 타입입니다.
따라서 orElseThrow가 가지는 의미는 Optional값의 isPresent() 메소드가 true를 반환하지 않을 경우 처리할 예외를 의미합니다! Spring에서 정말로 많이 사용되는 타입이니 기억해 두세요!

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 왜 저렇게 들여쓰기가 되는지 모르겠습니다ㅜㅜ 일자로 잘 될 거라 생각했는데 자꾸 저렇게 들여쓰기를 해주더라고요 ㅎㅎ... 억지로 고치다가 아직까지는 큰 영향이 없는 것 같아 냅두었습니다... orElseThrow가 꼭 필요한 이유가 궁금했는데 함께 코멘트 남겨주셔서 감사합니다!

System.out.println(avg);
}
}
6 changes: 6 additions & 0 deletions dayeon/advanced-java-assignment/src/T2/ArrayProcessing.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package T2;

@FunctionalInterface
public interface ArrayProcessing {
double apply(double[] array);
}
29 changes: 29 additions & 0 deletions dayeon/advanced-java-assignment/src/T2/Test2.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package T2;

public class Test2 {

public static double action(ArrayProcessing arrayProcessing) {
double[] array = {1, 2, 3, 4, 5, 6};

return arrayProcessing.apply(array);
}

public static void main(String[] args) {
double ans1 = action((array -> {
double result = 0;
for (int i = 1; i <= array.length; i++) {
if (array[(int)result] > array[i - 1]) { result = i; }
else { result = i - 1; }
} return array[(int)result];
}));

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저도 궁금해서 이 코드를 디버깅 해보면서 문제가 무엇인지 찾아보았습니다.

우선 첫 번째로 현재 주어진 배열에서 접근할 수 없는 인덱스의 값(array.length)로 배열에 접근할 가능성이 있다는 1차적인 문제가 있고
무엇보다 if문에서 array[result]의 값이 더 크다는 것이 결정되었으면 result 값이 변경되면 안되는데 완전히 다른 값으로 새롭게 저장되고 있습니다.

따라서 이 코드는 아예 지워버리시고 max라는 변수를 선언하고 0으로 초기화한 다음 배열을 순회하며 max 값보다 큰 값이면 max를 해당 값으로 저장하며 max를 구하시면 됩니다. if (max < array[i]) { max = array[i]; }

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

확인하여 수정하였습니다!
무조건 array를 사용하려 하다보니 이런 문제가 발생한 것 같습니다... 코멘트를 읽고 수정하며, 입력 값도 변경해보고 if문도 다시 살펴본 결과 말씀해주신 오류를 이해할 수 있었습니다. 이번 문제를 풀며 반복문을 통해 배열에 접근하는 부분을 특히 더 공부해야겠다는 생각이 듭니다... 자세한 코멘트 감사합니다!

System.out.println(ans1);

double ans2 = action((array -> {
double result = 0;
for (int i = 0; i < array.length; i++) {
result += array[i];
} return result / array.length;
}));
System.out.println(ans2);
}
}
27 changes: 27 additions & 0 deletions dayeon/advanced-java-assignment/src/T3/Test3.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package T3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test3 {
public static void main(String[] args) throws IOException {
int sum = 0;

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int count = Integer.parseInt(br.readLine());
try {
String[] strNum = br.readLine().split(" ");

for (int i = 0; i < count; i++) {
sum += Integer.parseInt(strNum[i]);
}
System.out.println("정수들의 합은 "+sum);
} catch (NumberFormatException e) {
System.out.println("예외가 발생했습니다!");
System.out.println("예외 정보: "+e);
}
br.close();
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

굳굳 잘 작성하셨습니다!!

53 changes: 53 additions & 0 deletions dayeon/database/db-assign.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
CREATE TABLE `Products` (
`productid` VARCHAR(255) NOT NULL,
`name` TEXT NULL,
`price` VARCHAR(255) NULL
);

CREATE TABLE `Customer` (
`custid` VARCHAR(255) NOT NULL,
`name` TEXT NULL,
`address` TEXT NULL,
`phone` TEXT NULL
);

CREATE TABLE `Orders` (
`orderid` VARCHAR(255) NOT NULL,
`orderdate` DATE NULL,
`productid` VARCHAR(255) NOT NULL,
`custid` VARCHAR(255) NOT NULL
);

ALTER TABLE `Products` ADD CONSTRAINT `PK_PRODUCTS` PRIMARY KEY (
`productid`
);

ALTER TABLE `Customer` ADD CONSTRAINT `PK_CUSTOMER` PRIMARY KEY (
`custid`
);

ALTER TABLE `Orders` ADD CONSTRAINT `PK_ORDERS` PRIMARY KEY (
`orderid`
);

INSERT INTO customer (custid, name, address, phone)
VALUES (1, ‘이영지’, ‘서울 송파구’, ‘010-1111-1111’),
(2, ‘안유진’, ‘서울 중구’, ‘010-2222-2222’),
(3, ‘미미’, ‘서울 강남구’, ‘010-3333-3333’),
(4, ‘이은지’, ‘서울 마포구’, ‘010-4444-4444’);

INSERT INTO products (productid, name, price)
VALUES (1, ‘스티커’, 2000),
(2, ‘키링’, 3000),
(3, ‘아크릴스텐드’, 5000),
(4, ‘인형’, 10000);

INSERT INTO orders (orderid, productid, custid, orderdate)
VALUES (1, 1, 1, ‘2024-03-05’),
(2, 2, 2, ‘2024-03-18’),
(3, 4, 3, ‘2024-04-05’);

SELECT customer.name, products.name, orders.orderdate
FROM orders
JOIN products ON products.productid = orders.productid
JOIN customer ON customer.custid = orders.custid;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

데이터베이스 부분은 깔끔하게 잘 설계하셨네요..!

Binary file added dayeon/database/erd.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.