1. 조건문
if 문
public class Hello {
public static void main(String[] args) {
int a = 10;
if(a>10) {
System.out.println(2);
}
else {
System.out.println(5);
}
}
}
if-else문
public class Hello {
public static void main(String[] args) {
int num = 83;
char score;
if(num >= 90) {
score='A';
}
else if(num >= 80) {
score='B';
}
else if(num >= 70) {
score='C';
}
else if(num >= 60) {
score='D';
}
else {
score='F';
}
System.out.println(score);
}
}
switch 문
public class Hello {
public static void main(String[] args) {
boolean run = true;
int balance = 0;
Scanner scanner = new Scanner(System.in);
while(run) {
System.out.println("----------------------------------");
System.out.println("1. 예금 2. 출금 3. 잔고 4. 종료");
System.out.println("----------------------------------");
System.out.println("선택 > ");
int num = scanner.nextInt();
switch(num) {
case 1:
System.out.println("예금엑 > ");
balance += scanner.nextInt();
break;
case 2:
System.out.println("출금액 > ");
balance -= scanner.nextInt();
break;
case 3:
System.out.println("잔고 > " + balance);
break;
case 4:
run = false;
break;
default:
break;
}
}
System.out.println("프로그램 종료");
}
}
2. 반복문
for 문
- 반복 횟수가 정해져 있을 때, 반복 횟수를 알고 있을 때 주로 사용
for(int i=0;i<10;i++) {
System.out.print("*");
}
- for문 실행될 때 초기화 식 i=0 이 제일 먼저 실행된다.
- 그런 다음 조건식 i<10 이 true 인지 확인해서 for 문 안의 실행문을 실행하고
- 실행을 마치면 증감식으로 돌아가서 i++ 을 한 다음 다시 조건식 i<10을 평가하여 true이면 실행문을 실행한다.
public class Hello {
public static void main(String[] args) {
for(int i=0;i<5;i++) {
for(int j=0;j<i+1;j++) {
System.out.print("*");
}
System.out.println();
}
}
}
while 문
- 조건에 따라 반복할 때 주로 사용
- while(조건식)이 true이면 계속해서 반복한다.
- do-while 문 : 실행문 먼저 실행하고 조건식 평가 do { 실행문 } while(조건식);
public class Hello {
public static void main(String[] args) {
int n = 26;
while(true) {
System.out.println(n);
if(n == 1) {
System.out.println("탈출 직전");
break;
}
n=n/2;
}
System.out.println("탈출");
}
}
continue
- 반복문을 종료하지 않고 계속 반복 수행한다. (<-> break)
for(int i=0;i<10;i++) {
if(i%2 != 0){
continue;
}
System.out.println(i);
}
'JAVA > Java Programming' 카테고리의 다른 글
[JAVA] DAO, DTO, VO 정리 (0) | 2023.09.16 |
---|---|
5장 참조 타입 (0) | 2021.09.13 |
3장 연산자 (0) | 2021.09.12 |
2장 변수와 타입 (0) | 2021.09.12 |
1장 자바 시작하기 (0) | 2021.09.12 |
댓글