본문 바로가기

프로그래머스 코딩(자바)/Level 1

Programmers Level 1 - 직사각형 별찍기

728x90

문제 설명

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

 
제한 조건
  • n과 m은 각각 1000 이하인 자연수입니다.

예시

입력

5 3

출력

*****
*****
*****

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        for(int i=0;i<b;i++) {
            for(int j=0;j<a;j++) {
                System.out.print("*");
            }
            System.out.println();
        }
        sc.close();
    }
}
cs

 

  행열을 입력받아 행과 열을 2중 반복문으로 반복하며 출력한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
import java.util.Scanner;
public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        for(int i=0;i<b;i++) {
            System.out.println("*".repeat(a));
        }
        sc.close();
    }
}
cs

 

1줄마다 출력하는 개수가 동일하므로 repeat()로 출력하였다. 반복문 1개로도 가능하다. 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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();
        IntStream.range(0,b).forEach(v->{
            System.out.println("*".repeat(a));
        });
        sc.close();
    }
}
cs

 

 

Stream으로도 풀어 보았다.

 

728x90