View
jungol.co.kr/bbs/board.php?bo_table=pbank&wr_id=2076&sca=2010
JUNGOL
www.jungol.co.kr
저번에 풀었던 구구단이랑 아주아주 흡사한 문제다.
그래서 저번에 짰던 코드를 참고해서 풀었다.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int e = sc.nextInt();
while ((s < 2 || s > 9) || (e < 2 || e > 9)){
System.out.println("INPUT ERROR!");
s = sc.nextInt();
e = sc.nextInt();
} // 범위 밖에 있는 숫자 입력 시 다시 입력
if (s < e) {
for (int i = 1; i <= 9; i++) {
for (int j = s; j <= e; j++) {
System.out.printf("%d * %d = %2d ", j, i, (j*i));
}
System.out.println();
}
} else {
for (int i = 1; i <= 9; i++) {
for (int j = s; j >= e; j--) {
System.out.printf("%d * %d = %2d ", j, i, (j*i));
}
System.out.println();
}
}
}
}
저번에 짠 코드는 이런 결과값이 나온다.
이번엔
이렇게 3개씩 끊어서 나오고, 단이 바뀌면 한 번 띄어줘야 한다.
if (s < e) {
for (int j = s; j <= e; j++) {
for (int i = 1; i <= 9; i++) {
System.out.printf("%d * %d = %2d ", j, i, (j * i));
}
System.out.println();
}
} else {
for (int j = s; j >= e; j--) {
for (int i = 1; i <= 9; i++) {
System.out.printf("%d * %d = %2d ", j, i, (j * i));
}
System.out.println();
}
}
중첩 for문의 순서를 서로 바꿔줬다.
예를들어 s가 3, j가 4라면 3단을 쫘르르 오른쪽으로 출력한 다음
j++되기 전에 System.out.println(); 으로 한 줄 띄어준다.
그럼 이렇게 출력된다.
하지만 한 줄에 3개씩 끊어서 출력해야하기 때문에 i를 3으로 나눈 몫이 0이면 한 줄 띄어주는 코드를 넣어준다.
for (int j = s; j <= e; j++) {
for (int i = 1; i <= 9; i++) {
System.out.printf("%d * %d = %2d ", j, i, (j * i));
if (i % 3 == 0) {
System.out.println();
}
}
}
이제 단이 바뀌면 한 줄 띄어주는 것만 추가하면 된다.
for (int j = s; j <= e; j++) {
for (int i = 1; i <= 9; i++) {
System.out.printf("%d * %d = %2d ", j, i, (j * i));
if (i % 3 == 0) {
System.out.println();
}
}
System.out.println();
}
}
별게 없다.. 그냥 s단이나 e단 끝나면 한 줄 띄어주면 된다.
완성 완성 ~~ ☆★☆
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int s = sc.nextInt();
int e = sc.nextInt();
while ((s < 2 || s > 9) || (e < 2 || e > 9)) {
System.out.println("INPUT ERROR!");
s = sc.nextInt();
e = sc.nextInt();
} // 범위 밖에 있는 숫자 입력 시 다시 입력
if (s < e) {
for (int j = s; j <= e; j++) {
for (int i = 1; i <= 9; i++) {
System.out.printf("%d * %d = %2d ", j, i, (j * i));
if (i % 3 == 0) {
System.out.println();
}
}
System.out.println();
}
} else {
for (int j = s; j >= e; j--) {
for (int i = 1; i <= 9; i++) {
System.out.printf("%d * %d = %2d ", j, i, (j * i));
if (i % 3 == 0) {
System.out.println();
}
}
System.out.println();
}
}
}
}
|
cs |
'Jungol' 카테고리의 다른 글
[Beginner] 1314 : 문자사각형2 (0) | 2021.02.21 |
---|---|
[Beginner] 2046 : 숫자사각형4 (0) | 2021.01.26 |
[Beginner] 1303 : 숫자사각형1 (0) | 2021.01.17 |
[Beginner] 1291 : 구구단 (0) | 2021.01.13 |
reply