😵 ~23.11.10
0616 | if~else, else if 문 연습 (바둑판 만들기)
unikue
2023. 6. 16. 17:39
✅ if : 우리가 흔히 쓰는 조건문
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 5; i++) {
if (i == 2) //프린트문보다 먼저 조건이 있다면 a2, 프린트문보다 조건이 늦게오면 2a
System.out.print("a ");
System.out.printf("%d ", i);// 0 1 a 2 3 4
}
System.out.println();
} // for ends
✅ if~else : else를 붙이면 if가 특정조건이 되면서 해당 값이 대체된다.
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 5; i++) {
// if else는 한문장으로 묶인다
if (i == 2)
System.out.print("a ");
else // else로 인해 0 1 a 3 4 로 출력된다
System.out.printf("%d ", i);
}
System.out.println();
} // for ends
✅ if~else if : [if else]가 한 묶음짜리 조건 1,2로 나눠지고 다음 if는 세번째 조건 (if문 단독 조건)이 되면서 만족할때 출력된다.
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 5; i++) {
// if else는 한문장으로 묶인다.
if (i == 2) // 3번째 if문을 쓰면 조건에 만족될때 출력되는 내용이 추가됨
System.out.print("a ");
else
System.out.printf("%d ", i); // if {...}else{...}로 묶여있는것과 동일.
if (i == 3)
System.out.print("b ");
} // 0 1 a 3 b 4
System.out.println();
} // for ends
👉 항상 if else if else를 묶음으로 쓰다가 이렇게 하나하나 쪼개서 순서를 옮기니 출력이 헷갈렸다. if else가 묶여있다는점을 잊지말 것.
✅ 배타적 조건을 넣을 때에는 if ~ else if ~ else를 쓴다
: 기존에 나와야할 값들이 대체가 되므로 조건을 넣어 print할때 많이 쓰인다.
for (int j = 0; j < 5; j++) {
for (int i = 0; i < 5; i++) {
if (i == 1)
System.out.print("a ");
else if (i == 2)
System.out.print("b ");
else if (i == 3)
System.out.print("c ");
else
System.out.printf("%d ", i);
}
System.out.println(); // 0 a b c 4
}
✅ 오목판 만들기
// 내가 한 풀이
for (int i = 0; i < 10; i++)
System.out.printf("%s", "┳");
System.out.println();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 10; j++)
System.out.printf("%s", "┼");
System.out.println();
}
for (int i = 0; i < 10; i++)
System.out.printf("%s", "┴");
System.out.println();
// --------------------------------------------
// 코드의 유연성을 위해 for문을 나누지 않고 하위 조건으로 넣어준다
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 10; j++) // for, if, elseif, else까지 모두 한 문장이므로 {중괄호}사용 안해도 됨.
if (i == 0)
System.out.printf("%s", "┳");
else if (i == 11)
System.out.printf("%s", "┴");
else
System.out.printf("%s", "┼");
System.out.println();
}
// 오목판 전체 만들기
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
if (i == 0 && j == 0)
System.out.printf("%s", "┏");
else if (i < 11 && j == 0)
System.out.printf("%s", "┣");
else if (i == 0 && j == 11)
System.out.printf("%s", "┓");
else if (i < 11 && j == 11)
System.out.printf("%s", "┫");
else if (i == 11 && j == 0)
System.out.printf("%s", "┗");
else if (i == 11 && j == 11)
System.out.printf("%s", "┛");
else if (i == 0) // 조건이 더 적은 케이스가 뒤에 나오도록 한다
System.out.printf("%s", "┳");
else if (i == 11)
System.out.printf("%s", "┴");
else
System.out.printf("%s", "┼");
}
System.out.println();
}
👉 좀더 보기 좋고 깔끔한 코드를 짜길 원한다면, if문 조건이 비슷한 것들끼리 하나로 묶고 그 안에서 다시 if문을 선언해주어도 좋을 듯.