2022.11.09 TIL

mil nil·2022년 11월 9일
0

TIL (Today I Learned)

목록 보기
8/74

1-17 객체지향 퀴즈(내가 한 답)

class 상속

Human.java

public class Human {
    String name;
    int age, speed, x, y;
    public Human(String name, int age, int speed, int x, int y) {
        this.name = name;
        this.age = age;
        this.speed = speed;
        this.x = x;
        this.y = y;
    }
    public Human(String name, int age, int speed) {
        this(name, age, speed,0,0);
    }
    public String Location() {
        return ("(" + x + ", " + y + ")");
    }
    protected void printWhoAmI() {
        System.out.println("My name is " + name + ". " + age + " aged.");
    }
    public void walk(int x, int y) {}
    public void run(int x, int y) {}
    public void swim(int x, int y) {}
}

GrandParent,java

public class GrandParent extends Human {
    public GrandParent(String name, int age) {
        super(name, age, 1);
    }
    @Override
    public void walk(int x, int y) {
        printWhoAmI();
        System.out.println("walk speed: " + speed);
        this.x = x;
        this.y = y;
        System.out.println("Walked to " + Location());
    }
}

Parent.java

public class Parent extends Human {
    public Parent(String name, int age) {
        super(name, age, 3);
    }
    @Override
    public void walk(int x, int y) {
        printWhoAmI();
        System.out.println("walk speed: " + speed);
        this.x = x;
        this.y = y;
        System.out.println("Walked to " + Location());
    }
    @Override
    public void run(int x, int y) {
        printWhoAmI();
        System.out.println("run speed: " + (speed + 2));
        this.x = x;
        this.y = y;
        System.out.println("Ran to " + Location());
    }
}

Child.java

public class Child extends Human {
    public Child(String name, int age) {
        super(name, age, 5);
    }
    @Override
    public void walk(int x, int y) {
        printWhoAmI();
        System.out.println("walk speed: " + speed);
        this.x = x;
        this.y = y;
        System.out.println("Walked to " + Location());
    }
    @Override
    public void run(int x, int y) {
        printWhoAmI();
        System.out.println("run speed: " + (speed + 2));
        this.x = x;
        this.y = y;
        System.out.println("Ran to " + Location());
    }
    @Override
    public void swim(int x, int y) {
        printWhoAmI();
        System.out.println("swim speed: " + (speed + 1));
        this.x = x;
        this.y = y;
        System.out.println("Swum to " + Location());
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        Human grandparent = new GrandParent("할아버지", 70);
        Human parent = new Parent("아버지", 45);
        Human child = new Child("아들", 20);
        Human[] humans = {grandparent, parent, child};
        for(Human human : humans) {
            System.out.println(human.name + ", " + human.age + ", " + human.speed);
        }
        System.out.println("---------------------------");
        for(Human human : humans) {
            if(human instanceof GrandParent) {
                human.walk(1,1);
                System.out.println("---------------------------");
            }
            if(human instanceof Parent) {
                human.walk(1, 1);
                System.out.println("---------------------------");
                human.run(2, 2);
                System.out.println("---------------------------");
            }
            if(human instanceof Child) {
                human.walk(1, 1);
                System.out.println("---------------------------");
                human.run(2, 2);
                System.out.println("---------------------------");
                human.swim(3, -1);
                System.out.println("---------------------------");
            }
        }
    }
}

잘 모르겠다...

예외, 에러처리

try-catch(-finally) 형식

public class Main {
    public static void main(String[] args) {
        int number = 10;
        int result;
        for (int i = 10; i >= 0; i--) {
            try {
                result = number / i;
                System.out.println(result);
            } catch (Exception e) {
                System.out.println("Exception발생: " + e.getMessage());
            } finally {
                System.out.println("항상 실행되는 finally 구문");
            }
        }
    }
}

try-with-resource 형식 (파일생성)

import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        try (FileOutputStream out = new FileOutputStream("test.txt")) {
            out.write("Hello Sparta".getBytes());
            out.flush();
        } catch (IOException e) {
            System.out.println("IOException 발생:" + e.getMessage());
            e.printStackTrace();
        }
    }
}

try-with-resource 형식 (기존파일 열기/닫기)

import java.io.FileOutputStream;
import java.io.IOException;
public class Main {
    public static void main(String[] args) throws IOException {
        FileOutputStream out = new FileOutputStream("test.txt")
        try {
            out.write("Hello Sparta".getBytes());
            out.flush();
        } catch (IOException e) {
            System.out.println("IOException 발생:" + e.getMessage());
            e.printStackTrace();
        }
        out.close();
    }
}

예외처리 퀴즈

class ArrayCalculation {
    int[] arr = { 0, 1, 2, 3, 4 };
    public int divide(int denominatorIndex, int numeratorIndex) throws ArithmeticException, ArrayIndexOutOfBoundsException {
        return arr[denominatorIndex] / arr[numeratorIndex];
    }
}
public class Main {
    public static void main(String[] args) {
        ArrayCalculation arrayCalculation = new ArrayCalculation();
            System.out.println("2 / 1 = " + arrayCalculation.divide(2, 1));
        try {
            System.out.println("1 / 0 = " + arrayCalculation.divide(1, 0)); // java.lang.ArithmeticException: "/ by zero"
        } catch (ArithmeticException arithmeticException) {
            System.out.println("잘못된 계산입니다: " + arithmeticException.getMessage());
        }
        try {
            System.out.println("Try to divide using out of index element = "
                    + arrayCalculation.divide(5, 0)); // java.lang.ArrayIndexOutOfBoundsException: 5
        } catch (ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException) {
            System.out.println("현재 배열 범위는 " + (arrayCalculation.arr.length - 1) + " 까지입니다.");
        }
    }
}

날짜, 시간 다루기

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class Main {
    public static void main(String[] args) {
        System.out.println("now usages");
        LocalDate date = LocalDate.now();
        LocalTime time = LocalTime.now();
        LocalDateTime dateTime = LocalDateTime.now();
        System.out.println(date);
        System.out.println(time);
        System.out.println(dateTime);
        System.out.println("of() usage");
        LocalDate dateOf = LocalDate.of(2022, 11, 9);
        LocalTime timeOf = LocalTime.of(12, 25, 5);
        System.out.println(dateOf);
        System.out.println(timeOf);
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        String shortFormat = formatter.format(LocalTime.now());
        System.out.println(shortFormat);
        DateTimeFormatter myFormatter = DateTimeFormatter.ofPattern("yyyy년 MM월 dd일");
        String myDate = myFormatter.format(LocalDate.now());
        System.out.println(myDate);
    }
}

_Format Style Link

날짜 계산

import java.time.LocalDate;
import java.time.Period;
public class Main {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        LocalDate birthday = LocalDate.of(1996,2,28);
        Period period = Period.between(today,birthday);
        System.out.println(period.getYears());
        System.out.println(period.getMonths());
        System.out.println(period.getDays());
    }
}

시간날짜 퀴즈

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
    public static void main(String[] args) {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("hh-mm-ss yyyy-MM-dd");
        String nowDateTime = format.format(LocalDateTime.now());
        System.out.println(nowDateTime);
    }
}

컬렉션

Lsit

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<Integer> integerList = new ArrayList<>();
        integerList.add(1);
        integerList.add(5);
        integerList.add(4);
        integerList.add(10);
        integerList.add(11);
        integerList.add(2);
        System.out.println(integerList);
        Collections.sort(integerList); // default 오름차순
        System.out.println(integerList);
        System.out.println(integerList.size()); // 크기
        integerList.remove(4); // 네 번째 제거
        System.out.println(integerList);
        for(int i=0; i<integerList.size();i++) {
            System.out.println(integerList.get(i));
        }
        for(int current: integerList) { // for 쉽게 돌리기
            System.out.println(current);
        }
    }
}

Set

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
    public static void main(String[] args) {
        Set<Integer> integerSet = new HashSet<>(); // 컬랙션 프레임워크에는 객체를 담음, 객체형 타입 Integer 사용, Set은 인터페이스, HashSet은 클래스
        integerSet.add(1);
        integerSet.add(4);
        integerSet.add(3);
        integerSet.add(2);
        integerSet.add(2);
        integerSet.add(1);
        integerSet.add(1);
        System.out.println(integerSet); // 중복 불가, 순서 없음
        Set<String> stringSet = new HashSet<>();
        stringSet.add("LA");
        stringSet.add("New York");
        stringSet.add("LasVegas");
        stringSet.add("San Francisco");
        stringSet.add("Chicago");
        stringSet.add("Seoul");
        System.out.println(stringSet); // 순서 없음
        stringSet.remove("Seoul"); // 서울 지우기
        System.out.println(stringSet);
        List<String> target = new ArrayList<>(); // 타겟 정하기
        target.add("San Francisco");
        stringSet.removeAll(target); // 정한 타켓 지우기
        System.out.println(stringSet);
        System.out.println("LA 포함되어있나요?" + stringSet.contains("LA")); // 포함 확인
        System.out.println("Seoul 포함되어있나요?" + stringSet.contains("Seoul"));
        System.out.println(stringSet.size()); // 크기
        stringSet.clear(); // 지우기
        System.out.println(stringSet);
    }
}

map

import java.util.HashMap;
import java.util.Map;
public class Main {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>(); // key, value 각각의 타입
        map.put(1, "apple");
        map.put(1, "apple1");
        map.put(1, "apple2");
        map.put(2, "berry");
        map.put(3, "cherry");
        map.put(4, "banana");
        System.out.println(map);
        System.out.println("1st in map: " + map.get(1));
        map.remove(1, "apple1"); // kew만 적으면 해당 key 삭제, 해당 key의 value만 삭제
        System.out.println(map);
        System.out.println(map.containsKey(2));
        System.out.println(map.containsValue("cherry"));
        map.clear();
        System.out.println(map);
    }
}

Stack

import java.util.Stack;
public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(1);
        stack.push(3);
        stack.push(7);
        stack.push(5);
        stack.push(9);
        System.out.println(stack);
        System.out.println(stack.peek()); // 꺼내서 확인하고 넣기
        System.out.println(stack.size());
        System.out.println(stack.pop()); // 꺼내기
        System.out.println(stack.size());
        System.out.println(stack.contains(1)); // 내용물 확인
        System.out.println(stack.empty()); //  비어있는지 확인
        stack.clear();
        System.out.println(stack.empty());
    }
}

ArrayDeque

import java.util.ArrayDeque;
	public class Main {
    	public static void main(String[] args) {
          ArrayDeque<Integer> arrayDeque = new ArrayDeque<>();
          arrayDeque.addFirst(1); // 맨 앞에 넣기
          arrayDeque.addFirst(12);
          arrayDeque.addFirst(33);
          System.out.println(arrayDeque);
          arrayDeque.addLast(8); // 맨 뒤에 넣기
          arrayDeque.addLast(7);
          arrayDeque.addLast(0);
          System.out.println(arrayDeque);
          arrayDeque.offerFirst(99); // 맨 앞에 넣기, 공간이 부족할 경우 False 반환
          arrayDeque.offerLast(99); // 맨 뒤에 넣기, 공간이 부족할 경우 False 반환
          System.out.println(arrayDeque.pop()); // 맨 앞 꺼내기, 빈 목록의 경우 Exception 반환
          System.out.println(arrayDeque.poll()); // 맨 앞 꺼내기, 빈 목록의 경우 null 반환
          System.out.println(arrayDeque);
    }
}

제네릭스
다양한 타입의 객체들을 다루는 메소드나 컬렉션 클래스에 컴파일 시의 타입 체크를 해주는 기능

- <T> == Type
- <E> == Element
- <K> == Key
- <V> == Value
- <N> == Number
- <R> == Result

람다
"식별자 없이 실행 가능한 함수" 즉, 함수의 이름을 따로 정의하지 않아도 곧바로 함수처럼 사용할 수 있다. 문법이 간결하여 보다 편리한 방식 (익명 함수라고도 함)
단점.
→ 람다를 사용하여서 만든 익명 함수는 재사용이 불가능합니다.
→ 람다만을 사용할 경우 비슷한 메소드를 중복되게 생성할 가능성이 있으므로 지저분해질 수 있습니다.

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("korea");
        list.add("japan");
        list.add("USA");
        list.add("France");
        Stream<String> stream = list.stream();
        stream.map(str -> {
                            System.out.println(str); // 원래대로 출력
                            return str.toUpperCase(); // 대문자로 변경
                        }).forEach(System.out::println); // 대문자로 출력, .forEach(it -> System.out.println(it))에서 간단하게 왼쪽처럼 전환 가능, 변수 하나일 경우
    }
}

Stream 예제1

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("서울");
        list.add("대전");
        list.add("부산");
        list.add("서울");
        List<String> result = list.stream()
                .limit(2) // 앞에서 두 개 외에 제거
                .collect(Collectors.toList()); // 결과를 리스트로 모음
        System.out.println(result);
        Set<String> set = list.stream()
                .filter("서울"::equals)
                .collect(Collectors.toSet());
        System.out.println(set);
    }
}

Stream 예제2

import java.util.Arrays;
import java.util.stream.Stream;
public class Main {
    public static void main(String[] args) {
        String[] arr =  {"SQL", "Java", "Python"};
        Stream<String> stringStream = Arrays.stream(arr);
        stringStream.forEach((System.out::println)); // collection이 아니어도 불러올 수 있음
    }
}

Stream 예제3 with map

import org.apache.commons.lang3.tuple.Pair;
import java.util.Arrays;
import java.util.List;
class Sale {
    String fruitName;
    int price;
    float discount;
    public Sale(String fruitName, int price, float discount) {
        this.fruitName = fruitName;
        this.price = price;
        this.discount = discount;
    }
}
public class Main {
    public static void main(String[] args) {
        List<Sale> sales = Arrays.asList(
                new Sale("Apple", 5000, 0.05f),
                new Sale("Orange", 5000, 0.02f),
                new Sale("Grape", 5000, 0)
        );
        sales.stream()
                .map(sale -> Pair.of(sale.fruitName, sale.price * (1-sale.discount)))
                .forEach(pair -> System.out.println(pair.getLeft() + " 실구매가: " + pair.getRight() + " 원 입니다."));
    }
}

Stream 예제4 with reduce

import java.util.Arrays;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        System.out.println(list.stream().reduce(0,Integer::sum));
    }
}

Stream 퀴즈

import java.util.Arrays;
import java.util.List;
public class Main {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("김정우", "김호정", "이하늘", "이정희", "박정우", "박지현", "정우석", "이지수");
        long total = names.stream()
                        .filter(name -> name.startsWith("이"))
                        .count();
        System.out.println("이 씨 성을 가진 사람 수: " + total);
    }
}

네트워킹
build.gradle에 붙여놓기 후 새로고침

implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.google.code.gson:gson:2.8.5'

RetrofitService (interface)

  import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface RetrofitService {
    @GET("/api/users/")
    Call<Object> getUsers(@Query("page") int page);
}

RetrofitClient (class)

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class RetrofitClient {
    private static final String BASE_URL = "https://reqres.in/";
    public static RetrofitService getApi() {
        return getInstance().create(RetrofitService.class);
    }
    private static Retrofit getInstance() {
        Gson gson = new GsonBuilder().setLenient().create();
        return new Retrofit.Builder().baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();
    }
}

Main

import retrofit2.Call;
import java.io.IOException;
public class Main {
    public static void main(String[] args) {
        Call<Object> result = RetrofitClient.getApi().getUsers(3);
        try {
            System.out.println(result.execute().body());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
profile
자바 배우는 사람

0개의 댓글