본문 바로가기
Language/JAVA

[JAVA] 쉽게 배우는 자바 프로그래밍_03장 제어문과 메서드

by 전전긍긍 2022. 4. 24.

본 포스팅은 쉽게 배우는 자바 프로그래밍 교재를 바탕으로 작성되었습니다.


Chapter 03. 제어문과 메서드

📍도전 과제

01. 키보드로 입력한 정수의 팩토리얼 값을 구하는 프로그램을 작성해 보자.

import java.util.Scanner;

public class Do_01 {
    public static void main(String[] args) {
        int result = 1;
        int n;
        Scanner in = new Scanner(System.in);

        System.out.print("팩토리얼 값을 구한 정수 : ");
        n = in.nextInt();

       /* while ( n > 0) {
            result *= n;
            n--;
        }*/

        while (true) {
            if (n > 0) {
                result *= n;
                n--;
            }
            else
                break;
        }

        System.out.println(result);
    }
}

02. 팩토리얼 값을 자주 계산한다면 메서드로 작성하는 것이 좋다. 이번에는 앞서 작성한 테스트 프로그램에서 팩토리얼 계산 과정을 메서드로 작성해 보자.

import java.util.Scanner;

public class Do3_02 {
    public static void main(String[] args) {
        int result;
        int n;
        Scanner in = new Scanner(System.in);

        System.out.print("팩토리얼 값을 구한 정수 : ");
        n = in.nextInt();

        result = factorial(n);
        System.out.println(result);
    }
    static int factorial(int x) {
        int r = 1;

        while(x > 0) {
            r *= x;
            x--;
        }
        return r;
    }
}

03. 팩토리얼 값뿐만 아니라 구간 팩토리얼 값을 계산하는 메서드를 오버로딩해 보자. 이번에는 편의상 키보드로 팩토리얼 인숫값을 받지 말고 테스트 프로그램에서 그냥 인숫값을 제공한다. 여기서 구간 팩토리얼 factorial(3, 5)는 3 * 4 * 5의 값을 의미한다.

public class Do3_02 {
    public static void main(String[] args) {

        System.out.println(factorial(5));
        System.out.println(factorial(1, 5));
        System.out.println(factorial(3, 5));
        System.out.println(factorial(10, 5));
    }
    static int factorial(int x) {
        int r = 1;

        while(x > 0) {
            r *= x;
            x--;
        }
        return r;
    }
    static int factorial(int x, int y) {
        int r = 1;

        while(x <= y) {
            r *= x;
            x++;
        }
        return r;
    }
}

📍프로그래밍 문제

01번. 키보드로 입력한 정수가 19 이상이면 '성년', 아니면 '미성년'을 출력하는 프로그램을 if - else 문을 시용헤 작성하라.

import java.util.Scanner;

public class Pro3_01 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();

        if (x >= 19)
            System.out.println("성년");
        else
            System.out.println("미성년");
    }
}

02번. 키보드로 등수를 입력받아 1등이면 '아주 잘했습니다.', 2~3등이면 '잘했습니다.', 4~6등이면 '보통입니다.', 그 외 등수이면 '노력해야겠습니다.'라고 출력하는 프로그램을 switch문을 사용해 작성하라.

import java.util.Scanner;

public class Pro3_02 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();

        switch (x) {
            case 1 -> System.out.println("아주 잘했습니다.");
            case 2, 3 -> System.out.println("잘했습니다.");
            case 4, 5, 6 -> System.out.println("보통입니다.");
            default -> System.out.println("노력해야겠습니다.");
        }
    }
}

03번. 키보드로 입력된 양의 정수 중에서 짝수만 덧셈해서 출력하는 코드를 do~while문을 사용해 작성하라. 단, 입력된 정수가 양수가 아니라면 입력을 종료한다.

import java.util.Scanner;

public class Pro3_02 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int i = 0;
        System.out.print("양의 정수를 입력하세요 : ");
        int x = in.nextInt();
        do {
            if ( x % 2 == 0)
                i += x;
            System.out.print("양의 정수를 입력하세요 : ");
            x = in.nextInt();
        } while (x > 0);
        System.out.println("입력한 양의 정수 중에서 짝수의 합은 " + i);
    }
}

04번. 다음 실행 결과를 출력하는 프로그램을 for문을 사용해 작성하라. (좌측 정렬 별 피라미드)

public class Pro3_04 {
    public static void main(String[] args) {
        for(int i = 0; i <= 5; i++) {
            for (int j = 0; j < i; j++)
                System.out.print("*");
            System.out.println();
        }
    }
}

05번. 각 변의 길이 합아 20 이하이며 각 변의 길이가 정수인 직각 삼각형의 모든 변을 구하라

public class Pro3_05 {
    public static void main(String[] args) {
        for (int a = 1; a < 20; a ++) {
            for (int b = 1; b < 20; b++) {
                for (int c = 1; c < 20; c++) {
                    if ( a * a + b * b == c * c) {
                        System.out.printf("%d, %d, %d", a, b, c);
                        System.out.println();
                    }
                }
            }
        }
    }
}

06번. 철수와 영희가 가위(s), 바위(r), 보(p) 게임을 한다. 다음 실행 결과와 같이 r, p, s 중 하나를 입력해 승자 또는 무승부를 출력하는 프로그램을 작성하라.

철수를 기준으로 가위바위보 프로그램이 돌아가도록 작성하였다.

equals() 메서드를 이용 → 문자열이 괄호 안에 있는 것과 같으면 if문 ok. 이런 식으로 문자열의 같음과 다름을 비교하였다.

import java.util.Scanner;

public class Pro3_06 {
    public static void main(String[] args) {
        Scanner in =new Scanner(System.in);

        System.out.print("철수 : ");
        String x = in.next();

        System.out.print("영희 : ");
        String y = in.next();

        //철수를 기준으로
        if(x.equals("r")) {
            if (y.equals("r"))
                System.out.println("무승부^^");
            else if (y.equals("s"))
                System.out.println("철수, 승!");
            else if (y.equals("p"))
                System.out.println("영희, 승!");
        }

        if(x.equals("s")) {
            if (y.equals("s"))
                System.out.println("무승부^^");
            else if (y.equals("p"))
                System.out.println("철수, 승!");
            else if (y.equals("r"))
                System.out.println("영희, 승!");
        }

        if(x.equals("p")) {
            if (y.equals("p"))
                System.out.println("무승부^^");
            else if (y.equals("r"))
                System.out.println("철수, 승!");
            else if (y.equals("s"))
                System.out.println("영희, 승!");
        }
    }
}

결과

07. 06번에서 프롬포트와 r, p, s를 입력하는 부분, 입력된 데이터에 따라 승자를 출력하는 부분을 각각 메서드로 작성하라. main() 메서드는 다음과 같다.

public static void main(String[] args) {
    String c = input("철수");
    String y = input("영희");
    whosWin(c, y);
}

메서드 작성하기

①input메서드/여기서는 return을 해주어야 함.(중요) input메서드는 영희와 철수가 r, p, s 중 하나를 입력받는 메서드이다.

②whosWin메서드/ 위의 코드와 다르게 작성해보았다. x.equals(y)는 영희와 철수의 입력값이 같을 때 무승부를 출력하게 하도록 equals() 메서드를 썼다. 그리고 반환값이 없어도 되기 때문에 반환타입은 void로 하였다. 

import java.util.Scanner;

public class Pro3_06 {
    public static void main(String[] args) {
        String c = input("철수");
        String y = input("영희");
        whosWin(c, y);
    }

    public static String input(String s) {
        Scanner in = new Scanner(System.in);
        System.out.print(s + " : ");
        s = in.next();
        return s;
    }

    public static void whosWin(String x, String y) {
        if (x.equals(y))
            System.out.println("무승부");
        else if ((x.equals("r")&&y.equals("s")) || (x.equals("s")&&y.equals("p")) || (x.equals("p")&&y.equals("r")))
            System.out.println("철수, 승!");
        else
            System.out.println("영희, 승!");
    }
}

결과

08. 다음과 같은 프로그램이 있다. factorial() 메서드를 화살표 case 레이블을 가진 switch문으로 작성하라.

(원래 내가 하고 싶었던 거)

factorial계산에서 예시로 5!이라면 5 * 4 * 3 * 2 * 1인데 1은 곱하나 마나 이므로 마지막에 2가 나왔을 때, 2를 반환하도록 (n % 2)를 했다. (n % 2)가 0이 되면 2를 반환하도록! 근데 자꾸 이상한 답이 나왔다. 왜 그런지 생각해보았는데, 예를 들었던 5!에서 4도 2로 나누어지기 때문에 제대로 된 계산이 되지 않았던 것이다. 할려면 n%2가 아니라 "n == 2이였을 때" 이런식으로 해야되는 거였다. 그리고 default를 이번 기회에 다시 개념을 잡은 것 같다. default는 일치되는 case 레이블이 없으면 실행된다. 나는 default 실행문이 기본적으로 전부 적용되는 줄 알았고 선택 사항이기 때문에 굳이 안써도 되는 줄 알고 처음에 쓰지 않아서 헤매였다. 즉 default는 if-else문의 else와 같은 것이라고 생각하면 된다. 

public class Pro3_08 {
    public static void main(String[] args) {
        System.out.println(factorial(5));
    }

    static int factorial(int n) {
        return switch (n % 2) {
            case 0 -> 2;
            default -> n * factorial(n - 1);
        };
    }
}

(답) n을 switch변수로 설정하여서 팩토리얼 계산의 마지막인 1이 되면 1을 return하도록 하고 case 레이블이 1이 아니면 default 실행문을 수행하도록 한다.

public class Pro3_08 {
    public static void main(String[] args) {
        System.out.println(factorial(5));
    }

    static int factorial(int n) {
        return switch (n) {
            case 1 -> 1;
            default -> n * factorial(n - 1);
        };
    }
}

(추가) 입력값을 받도록 코드를 추가하였다.

import java.util.Scanner;

public class Pro3_08 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.print("정수를 입력하세요 : ");
        int x = in.nextInt();
        System.out.println(factorial(x));
    }

    static int factorial(int n) {
        return switch (n) {
            case 2 -> 2;
            default -> n * factorial(n - 1);
        };
    }
}

결과

09. 다음은 foo() 메서드가 빠진 프로그램 일부와 실행 결과이다. foo()메서드를 완성하라.

public class Pro3_09 {
    public static void main(String[] args) {
        foo("안녕", 1);
        foo("안녕하세요", 1, 2);
        foo("잘 있어");
    }
    static void foo(String x, int y, int z) {
        System.out.println(x + " " + y + " " + z);
    }
    static void foo(String x, int y) {
        System.out.println(x + " " +  y);
    }
    static void foo(String x) {
        System.out.println(x);
    }
}

결과

10. 다음은 주어진 정수가 소수(prime)인지를 조사하는 프로그램의 일부이다. isPrime() 메서드를 완성하라. 여기서 소수는 1보다 크면서 1과 자신 외에는 나누지 않는 수이다.

여기서 입력값을 받는 새롭고 간단한 방식을 처음 봐서 왕신기하다.

항상 Scanner로 객체 생성 후 선언했는데, 한 줄로 이렇게 생성하고 선언하다니..! 기억기억⭐

int num = new Scanner(System.in).nextInt();

내 답에 자신이 없어서 여러 개의 수를 입력해보았는데 맞을 것 같다. (혹시 틀린 것 같다면 댓글로 알려주세요.)

import java.util.Scanner;

public class Pro3_10 {
    public static void main(String[] args) {
        System.out.print("양의 정수를 입력하세요 : ");
        int num = new Scanner(System.in).nextInt();
        if(isPrime(num))
            System.out.println(num + "은 소수입니다.");
        else
            System.out.println(num + "은 소수가 아닙니다.");
    }

    static boolean isPrime(int n) {
        for (int i = 2; i < n; i++) {
            if (n % i == 0) 
                return false;
        }
        return true;
    }
}

결과