반응형
※ 별찍기를 쉽게하는 방법 ※
공백이 별을 밀어낸다는 생각으로 구상하면 된다. 별과 공백을 자리를 차지하고 있다는 생각보다는 별이 왼쪽 정렬되어 있을 때 공백이 삼각형을 오른쪽으로 밀어낸다고 생각하면 쉽게 코드를 짤 수 있다.
(1) 오른쪽 직각 삼각형
package chap03;
public class plus {
public static void main(String[] args) {
for(int i = 0; i<10; i++) {
for(int j=10-(i+1); j>=0; j--) {
System.out.print(" ");
}
for(int j=0; j < (i+1); j++) {
System.out.print("*");
}
System.out.println();
}
}
}
/*
*
**
***
****
*****
******
*******
********
*********
**********
*/
(2) 숫자를 입력받아 왼쪽 직각 삼각형 출력
package chap03;
import java.util.Scanner;
public class plus {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("출력할 행의 개수 : ");
int temp = s.nextInt();
for(int i = 1; i<=temp; i++) {
for(int j=1; j <= i ; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
/*
출력할 행의 개수 : 5
1
12
123
1234
12345
*/
(4) 연속한 숫자 삼각형
package chap03;
import java.util.Scanner;
public class plus {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("출력할 행의 개수 : ");
int temp = s.nextInt();
for(int i = 1; i<=temp; i++) {
for(int j=1; j <= i ; j++) {
System.out.print(i);
}
System.out.println();
}
}
}
/*
출력할 행의 개수 : 5
1
22
333
4444
55555
*/
(5) 공백이 포함된 삼각형
package chap03;
import java.util.Scanner;
public class plus {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("출력할 행의 개수 : ");
int temp = s.nextInt();
int k=1;
for(int i = 1; i <= temp; i++) {
for(int j = 1; j <= i ; j++) {
System.out.printf("%-2d",k++);
}
System.out.println("");
}
}
}
/*
출력할 행의 개수 : 5
1
2 3
4 5 6
7 8 9 10
1112131415
*/
%-2d(왼쪽 정렬)
정삼각형
package chap03;
import java.util.Scanner;
public class plus {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("출력할 행의 개수 : ");
int temp = s.nextInt();
for(int i = 1; i <= temp; i++) {
for(int j = temp; j !=0; j--) {
System.out.print(" ");
}
for(int j = 1; j <= i; j++) {
System.out.print(i + " ");
}
System.out.println("");
temp --;
}
}
}
반응형
'JAVA > 2020 프로그램' 카테고리의 다른 글
[JAVA] 숫자 출현횟수 (0) | 2019.12.15 |
---|---|
[JAVA] 가위바위보 게임 (0) | 2019.12.08 |
[JAVA] 알파벳 프로그램 (0) | 2019.12.07 |
[JAVA] 소수점 두자리까지 같은 지 확인 (0) | 2019.12.07 |
[JAVA] 윤년계산하기 (0) | 2019.12.07 |