본문 바로가기

Coding Test/프로그래머스 연습

[JAVA] 직사각형 별찍기

문제 설명

이 문제에는 표준 입력으로 두 개의 정수 n과 m이 주어집니다.
별(*) 문자를 이용해 가로의 길이가 n, 세로의 길이가 m인 직사각형 형태를 출력해보세요.

 

👽내 코드

import java.util.Scanner;

class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        
        for(int j=0; j < b; j++){
            for(int i=0; i < a; i++){
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}

 

오랜만에 하는 별찍기!

print/println복습!

java.util.Scanner도 오랜만에 임포트.

 

🌈다른 풀이

import java.util.Scanner;
import java.util.stream.IntStream;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();

        StringBuilder sb = new StringBuilder();
        IntStream.range(0, a).forEach(s -> sb.append("*"));
        IntStream.range(0, b).forEach(s -> System.out.println(sb.toString()));
    }
}

 

StringBuilder를 이용한 방법

스트링빌더를 이용하면 바로 appen로 *을 추가

그리고 각각 a,b로 for each 돌려서 한다

IntStream.range를 통해 범위를 지정 > forEach 

마지막에 toString