https://www.acmicpc.net/problem/2444
Answer
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
int N = 0;
StringBuilder result = new StringBuilder();
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
N = Integer.parseInt(br.readLine());
} catch(IOException e) {
System.err.println("ERROR : " + e.getMessage());
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < N - i - 1; j++) {
result.append(" ");
}
for(int j = 0; j < 2 * i + 1; j++) {
result.append("*");
}
result.append("\n");
}
for(int i = N - 1; i > 0; i--) {
for(int j = 0; j < N - i; j++) {
result.append(" ");
}
for(int j = 0; j < 2 * i - 1; j++) {
result.append("*");
}
result.append("\n");
}
System.out.print(result);
}
}
Code Review
StringBuilder result = new StringBuilder();
한 줄씩 출력하는 것보다 문자열을 합쳐서 출력하는 것이 좋다고 생각해서 `StringBuilder` 클래스를 사용했다.
문자열을 합치기 위해서 `+` 연산을 사용한다면, 매 loop 마다 불필요한 객체가 쌓이게 되므로 성능이 좋지 않다.
2023.10.24 - [Study(JAVA)] - [Study(JAVA)] 문자열 합치기 (+, concat, StringBuilder, StringBuffer)
try(BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
N = Integer.parseInt(br.readLine());
} catch(IOException e) {
System.err.println("ERROR : " + e.getMessage());
}
`try-with-resources`로 try에 자원 객체를 전달하여, try 작업이 끝나면 자동으로 자원을 반환하도록 해준다.
`System.in`으로 사용자로부터 입력받은 데이터를 바이트 스트림으로 받는다.
`InputStreamReader` 클래스로 바이트 스트림을 문자 기반 스트림으로 변환해 준다.
`BufferedReader` 클래스로 문자 기반 스트림을 읽는다.
// 1
for(int i = 0; i < N; i++) {
// 1-1
for(int j = 0; j < N - i - 1; j++) {
result.append(" ");
}
// 1-2
for(int j = 0; j < 2 * i + 1; j++) {
result.append("*");
}
result.append("\n");
}
// 2
for(int i = N - 1; i > 0; i--) {
// 2-1
for(int j = 0; j < N - i; j++) {
result.append(" ");
}
// 2-2
for(int j = 0; j < 2 * i - 1; j++) {
result.append("*");
}
result.append("\n");
}
// 1
// 1-1 : '_'
// 1-2 : '*'
____*
___***
__*****
_*******
*********
// 2
// 2-1 : '_'
// 2-2 : '*'
_*******
__*****
___***
____*
Result