Online-Judge/Programmers
[Programmers] JAVA 직사각형 별찍기
nyangzzi
2022. 1. 3. 22:46
반응형
https://programmers.co.kr/learn/courses/30/lessons/12969
코딩테스트 연습 - 직사각형 별찍기
이 문제에는 표준 입력으로 두 개의 정수 n과 m이 주어집니다. 별(*) 문자를 이용해 가로의 길이가 n, 세로의 길이가 m인 직사각형 형태를 출력해보세요. 제한 조건 n과 m은 각각 1000 이하인 자연수
programmers.co.kr
1. n과 m을 int형으로 선언한 후 Scanner로 입력 받는다.
Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt();
2. 이중 for문으로 별을 찍을 때, 바깥쪽 for문이 세로를 의미하고 안쪽 for문이 가로를 의미한다.
가로의 길이가 n, 세로의 길이가 m이므로 바깥쪽 for문에 m까지, 안쪽 for문은 n까지 반복한다.

for(int i =0; i<m; i++){ for(int j = 0 ; j <n; j++){ System.out.print('*'); } System.out.println(); }
기본 print를 위해서는 System.out.print();을 사용하여 별을 출력한다.
한 줄을 모두 출력하면 다음 줄을 출력하기 위해 System.out.println(); 로 줄바꿈해준다.
전체코드
import java.util.Scanner; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); for(int i =0; i<m; i++){ for(int j = 0 ; j <n; j++){ System.out.print('*'); } System.out.println(); } } }
반응형