자바(JAVA)/미니 프로젝트 & 기초 공부

Java 기초 다시 공부하기 9주차 - 연습 문제 풀이 1

개발학생 2024. 9. 3. 15:27
반응형

1번 

- 입력된 정수 자료형의 숫자를 거꾸로 변환하는 프로그램 작성

입력 결과
12345 54321
-12345 -54321
100 1
0 0

 

public class Practice1 {
    public static void solution(int num) {
        int numReverse = 0;
        boolean isMinus = false;

        if (num < 0) {
            isMinus = true;
            num *= -1;
        }

        while (num > 0) {
            int r = num % 10;
            num /= 10;
            numReverse = numReverse * 10 + r;
        }

        System.out.println(isMinus ? numReverse * -1 : numReverse);
    }
    public static void main(String[] args){
        // Test code
        solution(12345);
        solution(-12345);
        solution(100);
        solution(0);
    }
}

2번

- 아스키 코드 알파벳에 대해서, 사용자가 입력한 알파벳의 대소문자를 변경하는 프로그램 작성

입력 출력
a A
b B
C c
D d

*아스키 코드

- 미국정보교환표준부호를 의미(American Standard Code for Information Interchange/ASCII)

- 문자를 사용하는 대부분의 장치에서 사용하며, 문자 인코딩 방식에 아스키를 기초로 두고 있음

- 특징

  • 7비트로 구성
  • 총 128개의 문자로 구성(출력 가능 제어문자 33개, 출력 가능 문자 95개)
  • 출력 가능한 문자들은 52개의 영문 알파벳 대소문자와 10개 숫자, 32개의 특수 문자, 1개의 공백 문자로 이루어짐 
import java.util.Scanner;

public class Practice2 {
    public static void solution() {
        Scanner sc = new Scanner(System.in);
        System.out.print("알파벳 입력: ");
        char input = sc.nextLine().charAt(0);
        int output = 0;

        int step = (int)'a' - (int)'A';

        if (input > 'a' && input <= 'z') {
            output = (int) input - step;
            System.out.print("대문자 변환: " + (char)output);
        } else if (input >= 'A' && input <= 'Z') {
            output = (int) input + step;
            System.out.println("소문자 변환: " + (char)output);
        } else {
            System.out.println("입력하신 값이 알파벳이 아닙니다.");
        }
    }

    public static void reference() {
        int a = (int)'a';
        System.out.println("a = " + a);
        int z = (int)'z';
        System.out.println("z = " + z);
        int A = (int)'A';
        System.out.println("A = " + A);
        int Z = (int)'Z';
        System.out.println("Z = " + Z);
        int etc = (int)'%';
        System.out.println("etc = " + etc);
    }

    public static void main(String[] args) {
        reference();    //아스키 코드 참고
        solution();
    }
}

 

3번

- String의 replace 기능을, replace, indexOf, contains를 사용하지 않고 구현

입력 문자열 from to 출력
"Hello Java, Nice to meet you! Java is fun!" "Java" "자바" "Hello 자바, Nice to meet you! 자바 is fun!"
"POP" "P" "W" "WOW"
public class Practice3 {
    public static String solution(char[] str, char[] find, char[] to) {
        int idx = 0;
        String replaceStr = "";
        char[] replaceBucket = str.clone();

        do {
            idx = findIndex(replaceBucket, find);

            if (idx != -1) {
                for (int i = 0; i < idx; i++) {
                    replaceStr += replaceBucket[i];
                }
                for (int i = 0; i < to.length; i++) {
                    replaceStr += to[i];
                }
                for (int i = idx + find.length; i < replaceBucket.length; i++) {
                    replaceStr += replaceBucket[i];
                }
                replaceBucket = replaceStr.toCharArray();
                replaceStr = "";
            }
        } while (idx != -1);

        replaceStr = new String(replaceBucket);
        return replaceStr;
    }

    public static int findIndex(char[] str, char[] find) {
        int idx = -1;
        boolean isMatch = false;

        for (int i = 0; i < str.length; i++) {
            if (str[i] == find[0] && str.length - i >= find.length) {
                isMatch = true;
                for (int j = 1; j < find.length; j++) {
                    if (str[i + j] != find[j]) {
                        isMatch = false;
                        break;
                    }
                }
            }

            if (isMatch) {
                idx = i;
                break;
            }
        }
        return idx;
    }

    public static void main(String[] args) {
        // Test code
        String str = "Hello Java, Nice to meet you! Java is fun!";
        String find = "Java";
        String to = "자바";

        // 기존 String replace
        System.out.println(str.replace(find, to));

        // 자체 구현 replace
        char[] strExArr = str.toCharArray();
        char[] findArr = find.toCharArray();
        char[] toArr = to.toCharArray();
        System.out.println(solution(strExArr, findArr, toArr));

        strExArr = "POP".toCharArray();
        findArr = "P".toCharArray();
        toArr = "W".toCharArray();
        System.out.println(solution(strExArr, findArr, toArr));
    }
}

4번

- 반복문과 조건문을 사용하여 5가지 별 찍기 구현

- 별 출력 행의 수 N과 별 타입 T가 주어질 때, 해당 별 모양을 출력하는 프로그램 작성(N은 홀수)

- 아래 모양은 N(별 출력 행의 수)이 3일 때의 출력 결과들 

타입 모양
1 ***
***
***
2 *
**
***
3   *
 **
***
4   *
 ***
*****
5   *
 ***
*****
 ***
  *

 

// 별 찍기
public class Practice4 {

    public static void type1(int n) {
        System.out.println("== Type1 ==");
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void type2(int n) {
        System.out.println("== Type2 ==");
        for(int i=0; i<n; i++) {
            for(int j=0; j<i+1; j++) {
               System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void type3(int n) {
        System.out.println("== Type3 ==");
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                if(j<n-i-1) {
                    System.out.print(" ");
                } else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void type4(int n) {
        System.out.println("== Type4 ==");
        for(int i=0; i<n; i++) {
            for(int j=0; j<n-i-1; j++) {
                System.out.print(" ");
            }

            for(int j=0; j<i*2+1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void type5(int n) {
        System.out.println("== Type5 ==");
        // 상단부
        for(int i=0; i<=n/2; i++) {
            for(int j=0; j<n/2-i; j++) {
                System.out.print(" ");
            }

            for(int j=0; j<i*2+1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }

        // 하단부
        for(int i=n/2; i>0; i--) {
            for(int j=0; j<n/2+1-i; j++) {
                System.out.print(" ");
            }

            for(int j=0; j<i*2-1; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        System.out.println();
    }

    public static void solution(int n, int type) {
        if(type == 1) {
            type1(n);
        } else if (type == 2) {
            type2(n);
        } else if (type == 3) {
            type3(n);
        } else if (type == 4) {
            type4(n);
        } else if (type == 5) {
            type5(n);
        }
    }
    public static void main(String[] args){
        //Test code
        solution(3,1);
        solution(3,2);
        solution(3,3);
        solution(3,4);
        solution(7,5);
    }
}

5번

- n개의 데이터가 height 배열에 주어졌고, 배열의 각 원소는 아래 그림과 같이 각 벽에 대한 높이를 의미함

  -> 이와 같이 높이 같들이 주어졌을 때,

       이 중에서 어떤 두 벽을 고르면 가장 많은 물을 담을 수 있는지를 확인하고 그때의 면적 출력

public class Practice5 {
    public static int solution(int[] height) {
        int left=0;
        int right=height.length - 1;
        System.out.println("right: "+right);
        int maxArea=0;

        while (left < right) {
            int x=(right-left);
            int y=height[left] < height[right] ? height[left] : height[right];
            System.out.println("int x,y: "+ x +","+y);
            int curArea = x*y;
            maxArea = maxArea > curArea ? maxArea : curArea;

            curArea = x * Math.min(height[left], height[right]);
            maxArea = Math.max(maxArea,curArea);
            System.out.println("maxArea: "+maxArea);

            if(height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return maxArea;
    }

    public static void main(String[] args) {
        //Test code
        int[] height = {1,8,6,2,5,4,8,3,7};
        System.out.println(solution(height));

        height = new int[]{5,3,9,2,1,1,1,1,1,1,1,1,1,2};
        System.out.println(solution(height));
    }
}

반응형