자바 입문 기초 알고리즘 구조

별찍기

ClapJeans 2023. 10. 5. 17:43

 

    public static void main(String[] args) {

        for (int i = 1; i < 5; i++) {

            for (int j = 0; j < 4 - i; j++) {
                System.out.print(" ");
            }

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

    }

 

 

Short Coding  chatGPT가 짜줌 ㅎ 

public static void main(String[] args) {
    for (int i = 1; i < 5; i++) {
        // Create a string with leading spaces
        String spaces = " ".repeat(4 - i);

        // Create a string with the 'i' value repeated (2 * i - 1) times
        String numbers = String.valueOf(i).repeat(2 * i - 1);

        // Combine the spaces and numbers strings and print
        System.out.println(spaces + numbers);
    }
}