PS/BOJ
2439/2442/2445/2522/10991/10992
easy16
2022. 4. 23. 12:13
공백 포함 별찍기
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String s="";
for (int i =0 ; i < n ; ++i) {
s+="*";
System.out.println(String.format("%"+n+ "s", s));
}
}
}
ex)
5
*
**
***
****
*****
가운데 정렬
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = n; i > 0; --i) {
for (int j = 1; j <= 2 * n - i; ++j) {
System.out.print((j < i) ? " " : "*");
}
System.out.println();
}
}
}
5
*
***
*****
*******
*********
tmp : 공백과 *의 경계를 나타내는 지점.
tmp를 잘 계산해야 코드가 간단해진다. (직접 i, j, tmp table 및 그림을 그려보면 이해가 빠름)
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int len = 2 * n;
for (int i = 1; i < len; ++i) {
for (int j = 1; j <= len; ++j) {
int tmp = (i <= n) ? i : len - i;
if (j > tmp && j <= len - tmp)
System.out.print(" ");
else
System.out.print("*");
}
System.out.println();
}
}
}
5
* *
** **
*** ***
**** ****
**********
**** ****
*** ***
** **
* *
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for ( int i = 1; i <= 2*n-1 ; ++i) {
for (int j = 1; j <= n ; ++j) {
int tmp =(i<=n)? n-i : i-n;
if( j > tmp)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println();
}
}
}
ex)
3
*
**
***
**
*
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1 ; i <= n ; ++i) {
boolean toggle=false;
for ( int j = 1 ; j <= 2*n-1 ; ++j) {
int tmp = n-i;
if (j > tmp && j <= 2*n-1-tmp && !toggle) {
System.out.print("*");
toggle=true;
} else {
if( j <= 2*n-1-tmp)//마지막 별 이후에는 공백을 출력해서는 안됨.
System.out.print(" ");
toggle=false;
}
}
System.out.println();
}
}
}
ex)
3
*
* *
* * *
import java.util.Scanner;
class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1 ; i <= n ; ++i) {
boolean emptyStart = (n>2 && i>=2 && i < n) ? true : false;
for ( int j = 1 ; j <= 2*n-1 ; ++j) {
int tmp = n-i;
if (j > tmp && j <= 2*n-1-tmp) {
if (emptyStart) {
if (j == tmp+1|| j ==2*n-1-tmp)
System.out.print("*");
else
System.out.print(" ");
} else {
System.out.print("*");
}
} else {
if( j <= 2*n-1-tmp)//마지막 별 이후에는 공백을 출력해서는 안됨.
System.out.print(" ");
}
}
System.out.println();
}
}
}
ex)
4
*
* *
* *
*******