상세 컨텐츠

본문 제목

JAVA 제어문 (if, switch, for, while, do~while)

BackEnd/JAVA

by H_Develop 2022. 7. 22. 16:20

본문

대부분 프로그램은 위에서 아래로 한 줄씩 실행(절차식 : batch 파일)되는 프로그램 흐름을 제어하는 기술.
( C에서는 goto가 흐름을 변경했었다. )

분기문 : if, switch
반복문 : for, while, do ~ while

 

if 문 보다 swich 문의 처리 속도가 빠르다

if 문

 

public class condition_if {

	public static void main(String[] args) {
		int n = 49;
		String str = null;	// String은 특수한 클래스이다. 초기값은 null.
		
		if(++n>=50) {	// () 안은 무조건 True | False 조건이어야 한다. 무한루프에 걸릴 수 있음.
			str = "n은 50 이상 입니다.";
		}	// {} 사이를 코드 블럭이라고 하며, 하나(suite)로 작동된다.
		else {
			str = "n은 50 미만 입니다.";
		}
		System.out.println(str);
		// if 조건이 true 이면 else를 실행하지 않고, 첫번째 코드블럭을 실행하고,
		// false 이면 else 코드블럭을 실행한다.
	}
}

 

다중 if 문
여러 조건 비교가 필요한 경우 사용.

 

import java.util.Scanner;
public class condition_if {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("점수 입력");
		int num = sc.nextInt();
		String str = ""; // String 문자열의 초기화

		if (num >= 90) { // 이 조건에 해당되면 아래는 수행하지 않음.
			str = "A";
		} else if (num >= 80) {
			str = "B";
		} else if (num >= 70) {
			str = "C";
		} else if (num >= 60) {
			str = "D";
		} else {
			str = "F";
		}
		System.out.println(str);
		// 위 메써드는 무조건 실행.
	}
}

 

 

 

Switch ~ case 문

 

if문은 괄호 안에 인자 값이 True or False 로 결정되는 조건식이다.
Switch는 조건이 아닌 비교할 값이 들어간다.
Case로 조건을 나열하며, 코드블럭을 벗어나기 위해 break;를 기술한다.
모든 조건에 충족하지 못하면 맨 아래 default 문을 실행한다.
if 문에 비해 처리속도가 빠르다.
if 문을 switch 문으로 대부분 대체 가능하다.

 

import java.util.Scanner;
public class Switch_Case {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("하고 싶은 것을 선택하세요"
				+ "1 : 게임하기"
				+ "2 : 게임소개"
				+ "3 : 게임종료");
		int n = sc.nextInt();
		switch (n) {	// 인자로 비교할 값이 들어가야 한다.
			case 1:		// 인자와 비교할 값이 들어간다.
				System.out.println("1: 게임하기");
				break;
			case 2:
				System.out.println("2: 게임소개");
				break;
			case 3:
				System.out.println("3: 게임종료");
				break;
			default :
				System.out.println("메뉴 선택이 올바르지 않아요.");
				break;
		}
		
//		if (n==1) {	// switch 문와 동일하게 사용 가능하다.
//			System.out.println("1: 게임하기");
//		} else if (n==2) {
//			System.out.println("2: 게임소개");
//		} else if (n==3) {
//			System.out.println("3: 게임종료");
//		} else {
//			System.out.println("메뉴 선택이 올바르지 않아요.");
//		}
	}
}

 

Switch를 이용하여 점수 별, 학점을 나타내시오.

 

import java.util.Scanner;
public class Switch_Case {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		System.out.println("성적을 입력해주세요");
		int n = sc.nextInt();
		int result = n / 10;

		switch (result) {	// 인자로 비교할 값이 들어가야 한다.
			case 10:		// 인자와 비교할 값이 들어간다.
				System.out.println("A");
				break;
			case 9:
				System.out.println("B");
				break;
			case 8:
				System.out.println("C");
				break;
			case 7:
				System.out.println("D");
				break;
			default :
				System.out.println("F");
				break;
		}
		
	}
}

 

 

for 문

중첩문

 

public class For_1 {
	public static void main(String[] args) {
		int i,j;
		for(j=1; j<10; j++) {
			for(i=1; i<=9; i++) {
				System.out.println(j+" x "+i + " = " + j*i);
			}
		}
	}
}


확장 for_문

for의 () 안에서 반복 범위를 지정하지 않고, 배열이나 셀렉션 클래스에서는 요소의 개수에 맞춰 반복시키는 경우를 말한다.

 

int[] a = {1,2,3,4}
for (int b:a);    이 구문에서 b는 요소를 대입하기 위한 변수로써 요소의 개수를 미리 지정하지 않아도 된다.
a에는 배열이나 컬렉션 클래스로 지정한다. 이렇게 하면 b에 a요소를 처음부터 차례대로 대입하는데,
몇 개의 요소인지는 몰라도 요소가 있는 한 처리를 계속하게 된다.
(python의 slicing 과 유사)

 

public class For_1 {
	public static void main(String[] args) {
//		String b; 이것으로 확장 for문에 변수를 넣으면 ERROR
		String[] season = {"Spring","Summer","Autumn","Winter"};
		
		for(String a : season) {
			System.out.println(a);
		}
	
	}
}

 

Spring
Summer
Autumn
Winter

 

 

다차원 배열 확장 for문

 

public class For_1 {
	public static void main(String[] args) {

		int[][] a = {
				{10,20,30},
				{40,50},
				{60}
		};

		System.out.println("a[0][0]= " + a[0][0] + " a[0][1]= " + a[0][1]+ " a[0][2]= " + a[0][2]);
		System.out.println("a[1][0]= " + a[1][0] + " a[1][1]= " + a[1][1]);
		System.out.println("a[2][0]= " + a[2][0]);
		
		for(int[] i : a) {
			for(int j : i) {
				System.out.print(j + " ");
			}
		}
	}
}

 

a[0][0]= 10 a[0][1]= 20 a[0][2]= 30
a[1][0]= 40 a[1][1]= 50
a[2][0]= 60
10 20 30 40 50 60 

관련글 더보기