JAVA 조건문과 반복문

if

1
2
3
4
5
6
7
8
9
if (조건부분 1) {
// 수행 부분 1
} else if (조건 부분 2) {
// 수행 부분 2
} else if (조건 부분 3) {
// 수행 부분 3
} else {
// 수행 부분 4
}

switch

1
2
3
4
5
6
7
8
9
10
11
switch (i) { // i : 불린이 아닌 식, 변수, 메소드
case 1:
System.out.println("1");
break;
case 2:
System.out.println("2");
break;
default:
System.out.println("0");
break;
}

while

1
2
3
while (조건 부분) {
수행 부분
}

10000 미만의 정수 중에서, 153의 배수중 가장 큰 값을 찾아 출력하세요.

내 풀이

1
2
3
4
5
6
7
8
9
10
11
12
public class Main {
public static void main(String[] args) {
int num = 10000;
int key = 153;
int count = 1;

while(key*count < num) {
count++;
}
System.out.println(key*(count - 1));
}
}

다른 풀이

1
2
3
4
5
6
7
8
9
10
11
public class Main {
public static void main(String[] args) {
int num = 10000;
int key = 153;

while(num % key > 0) {
num--;
}
System.out.println(num);
}
}

for

1
2
3
for (초기화식; 종결 제어식; 증감 제어식) {
// 수행부분
}

for문으로 구구단을 출력해보세요.
개인 풀이

1
2
3
4
5
6
7
8
9
public class Main {
public static void main(String[] args) {
for (int i = 1; i<=9; i++) {
for (int j = 1; j<=9; j++) {
System.out.println(i + " * " + j + " = " + (i*j));
}
}
}
}

다른 풀이

1
2
3
4
5
6
7
8
9
public class Main {
public static void main(String[] args) {
for (int i = 1; i<=9; i++) {
for (int j = 1; j<=9; j++) {
System.out.printf("%d * %d = %2d%n", i, j, i * j);
}
}
}
}

REFERENCE
코드잇 온라인 강의 자바 기초

  • © 2020-2025 404 Not Found
  • Powered by Hexo Theme Ayer