어제 하루 종일 아파서 골골거리다가 강의도 못 듣고, 그렇다고 아픈 데 제대로 못 쉬어서 능률도 안 나와서 조퇴했다 ㅠㅠ 아직까지 컨디션이 좋진 않았지만 열심히 했다
👉 5초 카운트 다운
public class main {
public static void main(String[] args) {
// write your code here
for (int i=5; i>=0; i--){
System.out.println("Countdown : " + i + "s");
}
}
}
👉 1~30 홀수의 합과 짝수의 합 구하기
public class main {
public static void main(String[] args) {
// write your code here
int sum1 = 0;
int sum2 = 0;
for (int i=0; i<=30; i++){
if(i % 2 == 0){
sum1 += (i+2);
}else{
sum2 += (i+2);
}
}
System.out.println(sum1);
System.out.println(sum2);
}
}
>>선생님 코드 : 왜 때문에 조건이 다르데 값은 같게 나오지?
public class main {
public static void main(String[] args) {
// write your code here
int sum1 = 0;
int sum2 = 0;
for (int i=0; i<30; i++){
int value = i+1;
if(value % 2 == 0){
sum1 += value;
}else{
sum2 += value;
}
}
System.out.println(sum1);
System.out.println(sum2);
}
}
객체 지향 언어
자바에서 제일 중요한 부분!!으로 이 부분만 제대로 이해하면 큰 산을 넘은 것🙃
1) Class, Method, instance
👉class 정의하고 그 안에 <model, color, price>라는 속성을 정의하여 Main 함수 안에 class Phone에 해당되는 객체를 생성
class Phone {
String model;
String color;
int price;
}
public class Main {
public static void main(String[] args) {
// write your code here
Phone galaxy = new Phone();
galaxy.model = "Galaxy Flip 4";
galaxy.color = "BoraPurple";
galaxy.price = 120;
Phone iphone = new Phone();
iphone.model = "iPhone 14 Pro";
iphone.color = "Purple";
iphone.price = 140;
System.out.println("Model : " + galaxy.model + ", Color : " + galaxy.color + ", Price : " + galaxy.price + "\n");
System.out.println("Model : " + iphone.model + ", Color : " + iphone.color + ", Price : " + iphone.price + "\n");
}
}
👉class에 메서드를 선언하고, main에서 인스턴스 생성
class Calculation {
int add(int x, int y){
return x+y;
}
int subtract(int x, int y){
return x-y;
}
}
public class Main {
public static void main(String[] args) {
// write your code here
Calculation calculation = new Calculation();
int addResult = calculation.add(1,2);
int subtractResult = calculation.subtract(10,2);
System.out.println(addResult);
System.out.println(subtractResult);
}
}
Calculation calculation = new Calculation();
이런 식으로 new class 를 생성해주는 것이 인스턴스이다.
int add(int x, int y){
return x+y;
}
int는 함수의 결과값이 전달되는 type으로 return type이라고 한다.
add는 함수의 이름이다.
(int x, int y)는 파라미터라고 하며 원하는 개수를 내 지정할 수 있다.
return은 실제로 내가 넘겨주고 싶은 값을 설정한다.
(return 1;로 설정할 수도 있고, 위의 코드처럼 더한 값을 넘겨줄 수도 있다.)
👉👉인스턴스의 기본 값들
class DefaultValueTest {
byte byteDefaultValue;
int intDefaultValue;
short shortDefaultValue;
long longDefaultValue;
float floatDefaultValue;
double doubleDefaultValue;
boolean booleanDefaultValue;
String referenceDefaultValue;
}
public class Main {
public static void main(String[] args) {
DefaultValueTest defaultValueTest = new DefaultValueTest();
System.out.println("byte default: " + defaultValueTest.byteDefaultValue);
System.out.println("short default: " + defaultValueTest.shortDefaultValue);
System.out.println("int default: " + defaultValueTest.intDefaultValue);
System.out.println("long default: " + defaultValueTest.longDefaultValue);
System.out.println("float default: " + defaultValueTest.floatDefaultValue);
System.out.println("double default: " + defaultValueTest.doubleDefaultValue);
System.out.println("boolean default: " + defaultValueTest.booleanDefaultValue);
System.out.println("reference default: " + defaultValueTest.referenceDefaultValue);
}
}
※ byte는 실제로 0이 아니라, 8bit 모두 0이어서 0으로 표시가 된 것.
👉 생성자 : 인스턴스가 생성될 때 사용되는 '인스턴스 초기화 메서드'이다. return 값이 없고, class과 동일해야 하는 것이 특징
class Phone {
String model;
String color;
int price;
}
public class Main {
public static void main(String[] args) {
// write your code here
Phone galaxy = new Phone();
Phone iphone = new Phone();
System.out.println("Model : " + galaxy.model + ", Color : " + galaxy.color + ", Price : " + galaxy.price + "\n");
System.out.println("Model : " + iphone.model + ", Color : " + iphone.color + ", Price : " + iphone.price + "\n");
}
}
이렇게 쓰면 new Phone()에 자동으로 변수가 할당된다. 그러나 아래처럼 생성자를 이용하면 처음과 같이 똑같이 도출된다.
class Phone {
String model;
String color;
int price;
//이 부분은 Alt+Inset 를 눌러서 편하게 입력할 수 있다.
Phone(String model, String color, int price){
this.model = model;
this.color = color;
this.price = price;
}
}
public class Main {
public static void main(String[] args) {
// write your code here
Phone galaxy = new Phone("Galaxy Flip 4", "BoraPurple", 120);
Phone iphone = new Phone("iPhone 14 Pro", "Purple", 140);
System.out.println("Model : " + galaxy.model + ", Color : " + galaxy.color + ", Price : " + galaxy.price + "\n");
System.out.println("Model : " + iphone.model + ", Color : " + iphone.color + ", Price : " + iphone.price + "\n");
}
}
🌟🌟🌟🌟🌟 상속 🌟🌟🌟🌟🌟
내가 제일 어려워 하는 부분
- 상속이란 기존의 클래스를 재사용하는 방식 중의 하나이다.
한 번 작성한 코드가 재사용이 필요하다면, 변경사항만 코드로 작성하므로 상대적으로 적은 양의 코드를 작성할 수 있다. 이렇게 코드를 재사용하면, 코드와 클래스가 많아질수록 관리가 용이하다는 장점이 있다. - 상속을 통해 클래스간의 계층구조를 만들게 된다.
- 상속의 특징
- 부모 클래스로에서 정의된 필드와 메서드를 물려받는다.
- 새로운 필드와 메서드를 추가할 수 있다.
- 부모 클래스에서 물려받은 메소드를 수정할 수 있다.
- 오직 하나의 클래스만을 상속받을 수 있다.
class Animal {
String name;
public void cry() {
System.out.println(name + " is crying.");
}
}
class Dog extends Animal {
Dog(String name){
this.name = name;
}
public void swim(){
System.out.println(name + " is swimming");
}
}
public class Main {
public static void main(String[] args){
Dog dog1 = new Dog("Coco");
dog1.cry();
dog1.swim();
Animal dog2 = new Dog("Mimi");
dog2.cry();
dog2.swim(); // 컴파일 에러. 실제 객체는 Dog지만 변수를 선언한 type은 Animal이기 때문에 Animal함수만 가능하다.
}
}
오버 로딩(overloading) vs 오버 라이딩(overriding)
👉 오버 로딩 : 한 클래스 내에 동일한 이름의 메서드(다른 내용)를 여러 개 정의하는 것
- 오버 로딩의 조건
- 메서드 이름이 동일해야 한다.
- 매개변수의 개수 혹은 타입이 달라야 한다.
반환 타입은 다르지만 int, long은 자료형 숫자 타입으로 같고, a, b, c / x, y, z 이 파라미터 이름은 중요하지 않다. type과 순서, 개수로 판단하기 때문에 위아래 코드가 같다고 판단하여 같은 메서드라고 여겨서 빨간 줄이 그어졌다.
public class Main {
public static void main(String[] args){
}
int add(int x, int y, int z) {
int result = x + y + z;
return result;
}
long add(int a, int b, long c) {
long result = a + b + c;
return result;
}
int add(int a, int b) {
int result = a + b;
return result;
}
}
이 코드들도 자료형 타입이 다르고, 개수가 다르기 때문에 오버 로딩의 조건에 부합한 오버 로딩이다.
👉 오버 라이딩 : 부모 클래스로부터 상속받은 메소드의 내용을 변경하는 것
- 오버라이딩의 조건
- 부모 클래스의 메소드와 이름이 같아야 한다.
- 부모 클래스의 메소드와 매개변수가 같아야 한다.
- 부모 클래스의 메소드와 반환타입이 같아야 한다.
class Animal {
String name;
String color;
public void cry() {
System.out.println(name + " is crying.");
}
}
class Dog extends Animal {
Dog(String name) {
this.name = name;
}
@Override
public void cry() {
System.out.println(name + " is barking!");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog("Coco");
dog.cry();
}
}
🚨오버로딩 : 기존에 없는 새로운 메소드를 정의하는 것❣️
🚨오버라이딩 : 상속받은 메소드의 내용을 변경하는 것❣️
Python
👉 알고있는 기본
a^b (a 제곱 b) 표현하기
a=3
b=2
print(a**b)
# 9
문자열
text = 'abcdefghijk'
result1 = text
result2 = len(text)
result3 = text[:3]
result4 = text[3:]
result5 = text[:]
print(result1)
print(result2)
print(result3)
print(result4)
print(result5)
문자열 그대로
길이
3번째 전에 자르기
3번째부터 자르기
복사
myemail = 'hello@sparta.com'
result1 = myemail.split('@')
result2 = myemail.split('@')[1]
result3 = myemail.split('@')[1].split('.')
result4 = myemail.split('@')[1].split('.')[0]
print(result1)
print(result2)
print(result3)
print(result4)
@를 기준으로 자르기
@를 기준으로 자른 것 중 1번째 선택
. 을 기준으로 자르기
. 을 기준으로 자른 것 중 0번째 선택
Q1) 다음 코드를 이용하여 spa만 나오게 하기
text = 'sparta'
result = text
print(result)
정답
text = 'sparta'
result = text[:3]
print(result)
text = 'sparta'
result = text.split('r')[0]
print(result)
Q2) 다음 코드를 이용하여 지역 번호만 나오게 자르기
phone = '02-123-1234'
result = phone
print(result)
정답
phone = '02-123-1234'
result = phone[:2]
print(result)
phone = '02-123-1234'
result = phone.split('-')[0]
print(result)
👉 👉 내가 몰랐던 파이썬 시~작!
👉리스트 (list)와 딕셔너리 (dictionary)
- 리스트는 순서가 중요하게 값을 담는 방법이고
딕셔너리는 key:value 로 값을 담는 방법(이름 : ㅇㅇㅇ, 나이: 00 …)
리스트 덧붙이거나, 잘라내기
a_list = (1,2,3,4,5)
b_list = (4,5,'pear',['apple','annas'])
result1 = a_list[:3]
result2 = a_list[-1]
result3 = len(a_list)
result4 = (100 in a_list)
print(b_list[3][1])
print(result1)
print(result2)
print(result3)
print(result4)
리스트 정렬하기
a = [2, 5, 3]
a.sort()
print(a) # [2, 3, 5]
a.sort(reverse=True)
print(a) # [5, 3, 2]
리스트 해당 요소가 있는지 알아보기
a = [2, 1, 4, "2", 6]
print(1 in a) # True
print("1" in a) # False
print("2" in a) # True
print(0 not in a) # True
리스트와 딕셔너리 혼합 사용 가능
a_dict = {'name':'bob', 'age':27, 'friend':['RM','J-HOPE']}
result=a_dict['friend'][0]
print(result) #RM
딕셔너리도 리스트와 같다.
a_dict = {'name':'bob', 'age':27, 'friend':['RM','J-HOPE']}
result=a_dict['friend'][0]
a_dict['height']=180
print(result) #RM
print(a_dict) #{'name': 'bob', 'age': 27, 'friend': ['RM', 'J-HOPE'], 'height': 180}
print('weight' in a_dict) #False
딕셔너리
people = [
{'name': 'bob', 'age': 27},
{'name': 'jane', 'age': 31}
]
print(people[1]['age']) #31
Q) 아래의 코드로 smith의 science 점수를 출력하기
내가 쓴 코드
people = [
{'name': 'bob', 'age': 20, 'score':{'math':90,'science':70}},
{'name': 'carry', 'age': 38, 'score':{'math':40,'science':72}},
{'name': 'smith', 'age': 28, 'score':{'math':80,'science':90}},
{'name': 'john', 'age': 34, 'score':{'math':75,'science':100}}
]
print(people[2]['score']['science'])