ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 쉽게 배우는 자바 프로그래밍 2판 10장 프로그래밍 문제 Part.1 (1번 ~ 5번)
    JAVA/연습문제 2022. 11. 2. 20:36
    반응형

     

    # 개발 공부하는 초보자가 작성한 답안이니 정답이 아닐 수 있습니다!!!

     

     

    1. 다음은 문자열 배열에 포함된 원소를 Arrays.sort() 메서드로 정렬하는 테스트 프로그램의 실행 결과이다. 테스트 프로그램은 정렬할 때 문자열의 대소문자를 구분하지 않는다. 람다식을 이용한 테스트 프로그램과 메서드 참조를 이용한 테스트 프로그램을 각각 작성하라.

    📢주어진 결과값📢
    정렬 전 : K o r e a n
    정렬 후 : a e K n o r
    🧤정답🧤
    public class TestSortPg {
        public static void main(String[] args) {
    		SortGab c;
    		BayolGab s = new BayolGab();
    		System.out.println("===메서드 참조 방법===");
    		System.out.print("정렬 전 : ");
    		c = s::transchamjoGab;
    		System.out.println(c.referenceGab());
    
    		System.out.print("정렬 후 : ");
    		c = s::transchamjoGab2;
    		System.out.println(c.referenceGab());
    
    		BayolGab s2 = new BayolGab();
    		System.out.println("===람다식 방법===");
    		System.out.print("정렬 전 : ");
    		c = () -> s2.transchamjoGab();
    		System.out.println(c.referenceGab());
    
    		System.out.print("정렬 후 : ");
    		c = () -> s2.transchamjoGab2();
    		System.out.println(c.referenceGab());
        }
    }
    
    
    
    import java.util.Arrays;
    
    public class BayolGab {
    	String[] strBayol2 = { "K", "o", "r", "e", "a", "n" };
    
    	String transchamjoGab() {
    		return toString();
    	}
    
    	String transchamjoGab2() {
    		Arrays.sort(strBayol2, String.CASE_INSENSITIVE_ORDER);
    		return toString();
    	}
        
    	public String toString() {
    		return Arrays.toString(strBayol2).replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(",", "");
    	}
    }
    
    public interface SortGab {
        String referenceGab();
    }

     

     

    2. 다음과 같은 테스트 프로그램의 일부와 실행 결과가 있다. Wordable 타입의 배열 원소를 람다식으로 구성한 테스트 프로그램을 작성하라.

    📢주어진 조건📢
    interface Wordable {
    	void word();
    }
    
    public class WordableTest {
    	public static void main(String[] args) {
    		Wordable[] m = { 
                    // 필요한 코드   
            };
    
    		// 반복문
    	}
    }
    🧤정답🧤
    interface Wordable {
    	void word();
    }
    
    public class WordableTest {
    	public static void main(String[] args) {
    		Wordable[] m = { () -> System.out.println("가위"), () -> System.out.println("나비"),
    				() -> System.out.println("다리") };
    
    		for (Wordable w : m) {
    			w.word();
    		}
    	}
    }

     

     

    3. 다음은 주어진 숫자에 따라 1이면 숫자와 'apple', 2 이상이면 숫자와 'apples'를 타나태는 실행 결과이다. 함수형 인터페이스 Consumer를 이용한 테스트 프로그램을 작성하라.

    📢주어진 결과값📢
    3 apples.
    1 apple.
    🧤정답🧤
    import java.util.List;
    
    public class ConChamjoGab {
    	public static final List<Integer> liGab = List.of(3, 1);
    }
    
    import java.util.Scanner;
    import java.util.function.Consumer;
    
    public class ConsumerTest {
    	public static void main(String[] args) {
    		Scanner inScanner = new Scanner(System.in);
    		Consumer<Integer> cns = x -> {
    			if (x >= 2) {
    				System.out.print(x + " apples.");
    			} else {
    				System.out.print(x + " apple.");
    			}
    			System.out.println();
    		};
    
    		for (int i = 0; i < 2; i++) {
    			int intGab = inScanner.nextInt();
    			cns.accept(intGab);
    		}
    		Consumer<Integer> cns2 = x -> {
    			if (x >= 2) {
    				System.out.print(x + " apples.");
    			} else {
    				System.out.print(x + " apple.");
    			}
    			System.out.println();
    		};
    
    		for (int i = 0; i < 2; i++) {
    			cns2.accept(ConChamjoGab.liGab.get(i));
    		}
    	}
    }

     

     

    4. 주어진 정수에 대하여 길이를 반환하는 프로그램을 두 가지 방식인 ToIntFunction과 UnaryOperator 인터페이스를 사용하여 작성하되, 테스트 과정도 포함하라.

    📢주어진 결과값📢
    ToIntFunction :
    length(10) = 2
    length(100) = 3
    length(1000) = 4
    
    UnaryOperator :
    length(10) = 2
    length(100) = 3
    length(1000) = 4
    🧤정답🧤
    import java.util.function.ToIntFunction;
    import java.util.function.UnaryOperator;
    
    public class FunAndOpeTest {
    	public static void main(String[] args) {
    		int[] ganInt = { 10, 100, 1000 };
    
    		ToIntFunction<String> tif = x -> x.length();
    		UnaryOperator<Integer> uor = x -> {
    			Integer i;
    			for (i = 0; x != 0; i++)
    				x /= 10;
    			return i;
    		};
    
    		System.out.println("ToIntFunction :");
    		for (int i = 0; i < ganInt.length; i++) {
    			System.out.println("length(" + ganInt[i] + ") = " + tif.applyAsInt(String.valueOf(ganInt[i])));
    		}
    
    		System.out.println("\nUnaryOperator :");
    		for (int i = 0; i < ganInt.length; i++) {
    			System.out.println("length(" + ganInt[i] + ") = " + uor.apply(ganInt[i]));
    		}
    	}
    }

     

     

    5. 다음과 같은 startsWith() 메서드를 포함하는 FirstString 클래스가 있다. 메서드 참조와 함수형 인터페이스 Operator를 이용하여 문장의 첫 문자를 String 타입으로 반환하는 프로그램을 작성하라. 단, 테스트할 문자열 s는 모두 알파벳으로 구성된다고 가정한다.

    📢주어진 조건 1📢
    class FirstString {
    	String startsWith(String s) {
        	return Character.toString(s.charAt(0));
        }
    }
    🧤정답🧤
    import java.util.function.UnaryOperator;
    
    public class FirstStringTest {
    	public static void main(String[] args) {
        	//인스턴스 메서드를 포함한 클래스를 호출해야지 아래 인스턴스 메서드 참조가 가능하다.
    		FirstString f = new FirstString();
    
    		UnaryOperator<String> uoprt = f::startsWith;
    		System.out.println(uoprt.apply("야야야야양"));
    	}
    }
    
    class FirstString {
    	String startsWith(String s) {
    		return Character.toString(s.charAt(0));
    	}
    }

     

     

    반응형

    댓글

Designed by Tistory.