점프 투 자바(Java)/23년 1월

1월 27일(금) - 7장 연습문제

C0MPAS 2023. 1. 27. 14:24

7장 연습문제

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

1번 - 패키지 오류 수정하기

package house;

public class HousePark {
    protected String lastname = "park";

    public String getLastname() {
        return this.lastname;
    }
}
// 수정 전
import HousePark;

public class Sample {
    public static void main(String[] args) {
        HousePark housePark = new HousePark();
        System.out.println(housePark.getLastname());
    }
}

-> HousePark 클래스를 찾을 수 없다는 오류가 발생

-> import 문을 수정하여 오류를 해결

// 수정 후
import house.HousePark;

public class Sample {
    public static void main(String[] args) {
        HousePark housePark = new HousePark();
        System.out.println(housePark.getLastname());
    }
}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

2번 - 예외처리

import java.util.ArrayList;
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        int result = 0;
        try {
            int[] a = {1, 2, 3};
            int b = a[3];
            ArrayList c = new ArrayList(Arrays.asList("3"));
            int d = (int) c.get(0);
            int e = 4 / 0;
        } catch (ClassCastException e) {
            result += 1;
        } catch (ArithmeticException e) {
            result += 2;
        } catch (ArrayIndexOutOfBoundsException e) {
            result += 3;
        } finally {
            result += 4;
        }
        System.out.println(result); // result 의 값은 무엇일까?
    }
}

-> int b = a[3]에서 ArrayIndexOutOfBoundsException 이 발생할 것 이다

-> 왜냐하면 a[0]부터 a[2]까지만 존재하기 때문이다

-> 결과적으로 result +=3 그리고 finally에 의해서 result+=4 가 실행되므로 최총 result 값은 7이다

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

3번 - 스레드 적용하기

(풀이 참조 -> 추가학습 필요)

// Thread 적용 전
class HeavyWork {
    String name;

    HeavyWork(String name) {
        this.name = name;
    }

    public void work() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(100);  // 0.1 초 대기한다.
            } catch (Exception e) {
            }
        }
        System.out.printf("%s done.\n", this.name);
    }
}

public class Sample {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 1; i < 5; i++) {
            HeavyWork w = new HeavyWork("w" + i);
            w.work();
        }
        long end = System.currentTimeMillis();
        System.out.printf("elapsed time:%s ms\n", end - start);
    }
}

 

// Thread 적용 후
import java.util.ArrayList;
class HeavyWork implements Runnable{
    String name;

    HeavyWork(String name) {
        this.name = name;
    }

    @Override
    public void run(){
        work();
    }

    public void work() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(100);  // 0.1 초 대기한다.
            } catch (Exception e) {
            }
        }
        System.out.printf("%s done.\n", this.name);
    }
}

public class Sample{
    public static void main(String[] args) throws InterruptedException{
        long start = System.currentTimeMillis();
        ArrayList<Thread> threads = new ArrayList<>();
        for (int i = 1; i < 5; i++) {
            Thread t = new Thread(new HeavyWork("w" + i));
            threads.add(t);
            t.start();
        }
        for(Thread t : threads){
            t.join();
        }
        long end = System.currentTimeMillis();
        System.out.printf("elapsed time:%s ms\n", end - start);
    }
}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

4번 - 홀수에만 2를 곱하여 리턴하기

(함수형 프로그래밍 사용)

// 함수형 프로그래밍 적용 전
import java.util.ArrayList;

public class Sample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        ArrayList<Integer> temp = new ArrayList<>();
        for (int num : numbers) {
            if (num % 2 == 1) {  // 홀수이면 
                temp.add(num * 2);  // 2를 곱하여 temp에 담는다.
            }
        }

        // 정수 리스트를 정수배열로 변환한다.
        int[] result = new int[temp.size()];
        for (int i = 0; i < temp.size(); i++) {
            result[i] = temp.get(i);
        }
    }
}

 

// 함수형 프로그래밍(Stream) 적용 후
import java.util.Arrays;

public class Sample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int[] result = Arrays.stream(numbers)
                .filter( (a) -> a%2 == 1)
                .map( (a) -> a*2)
                .toArray()
                ;
        
    }
}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

5번 - 음수 제거하기

(함수형 프로그래밍 사용)

import java.util.Arrays;

public class Sample{
    public static void main(String[] args){
        int[] numbers = {1, -2, 3, -5, 8, -3};
        int[] result = Arrays.stream(numbers)
                .filter( (a)-> a>=0)
                .toArray()
                ;
    }
}

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ