Java

조건문

'비교 수업'에서 비교 연산의 결과로 참(true)이나 거짓(false)을 얻을 수 있다고 배웠다. 불린은 조건문에서 핵심적인 역할을 담당하는데 이 불린 값을 기준으로 실행 흐름을 제어하기 때문이다.

조건문

조건문이란 주어진 조건에 따라서 애플리케이션을 다르게 동작하도록 하는 것으로 프로그래밍의 핵심 중의 하나라고 할 수 있다.

조건문의 문법

프로그래밍에서 문(文, Statements)은 문법적인 완결성을 가진 하나의 완제품이라고 할 수 있다. if문, for문, while문등이 여기에 해당한다. 절(節마디절, clause)은 문(statements)를 구성하고 있는 부품이라고 할 수 있다. 곧 배우게 된다. 물론 이러한 문법적인 개념은 이해를 돕기 위한 것일 뿐 암기해야 할 것은 전혀 아니다.

if

조건문은 if로 시작한다. 아래 그림을 보자. if 뒤의 괄호를 if절이라고 부르고, 중괄호가 감싸고 있는 구간을 then 절이라고 부르겠다. 조건문에서는 if 절의 값이 true일 때 then 절이 실행된다. if 절이 false이면 then 절은 실행되지 않는다.

아래 예제의 실행결과는 'result : true'다. if 뒤에 True가 왔기 때문이다. 아래의 실행 결과는 화면에 result : true를 출력한다. (실행)

package org.opentutorials.javatutorials.condition;

public class Condition1Demo {

    public static void main(String[] args) {
		if(true){
			System.out.println("result : true");
		}
	}

}

다음 예제는 아무것도 출력하지 않을 것이다. if절이 false이기 때문이다.

if(false){
	System.out.println("result : true");
}   

다음 예제를 보자. 결과는 12345를 출력할 것이다. (실행)

package org.opentutorials.javatutorials.condition;

public class Condition2Demo {

    public static void main(String[] args) {
		if (true) {
			System.out.println(1);
			System.out.println(2);
			System.out.println(3);
			System.out.println(4);
		}
		System.out.println(5);
	}

}

다음 예제를 실행해보자. 결과는 5만 출력될 것이다. (실행)

if(false){
	System.out.println(1);
	System.out.println(2);
	System.out.println(3);
	System.out.println(4);
}
System.out.println(5);

else

if만으로는 좀 더 복잡한 상황을 처리하는데 부족하다. 아래의 그림처럼 if-else절은 if 절의 값이 true일 때 then절이 실행되고, false일 때 else절이 실행된다.

아래 예제를 보자. 결과는 1이다. (실행)

package org.opentutorials.javatutorials.condition;

public class Condition3Demo {

    public static void main(String[] args) {
		if (true) {
			System.out.println(1);
		} else {
			System.out.println(2);
		}

	}

}

다음 예제의 결과는 2다. (실행)

if(false){
	System.out.println(1);
} else {
	System.out.println(2);
}

else if

else if절을 이용하면 조건문의 흐름을 좀 더 자유롭게 제어할 수 있다. if절의 값이 true라면 then절이 실행된다. false라면 else if절로 제어가 넘어간다. else if절의 값이 true라면 else if then절이 실행된다. false라면 else 절이 실행된다. else if절은 여러 개가 복수로 등장할 수 있고, else절은 생략이 가능하다. else 절이 else if 절보다 먼저 등장할 수는 없다.

아래 예제를 보자. 결과는 2다. (실행)

package org.opentutorials.javatutorials.condition;

public class ElseDemo {

    public static void main(String[] args) {
		if (false) {
			System.out.println(1);
		} else if (true) {
			System.out.println(2);
		} else if (true) {
			System.out.println(3);
		} else {
			System.out.println(4);
		}

	}

}

다음 예제의 결과는 3이다. (실행)

if(false){
	System.out.println(1);
} else if(false) {
	System.out.println(2);
} else if(true) {
	System.out.println(3);
} else {
	System.out.println(4);
}

다음 예제의 결과는 4다. (실행)

if(false){
	System.out.println(1);
} else if(false) {
	System.out.println(2);
} else if(false) {
	System.out.println(3);
} else {
	System.out.println(4);
}

변수와 비교연산자 그리고 조건문

지금까지 배운 부품들을 결합해서 작은 프로그램을 만들어보자. 예제에서 사용할 부품은 변수, 비교연산자, 조건문이다. 사용자가 입력한 아이디 값을 체크하는 프로그램을 만들어 볼 것이다. ID의 값으로 egoing을 입력해보고, 다른 값도 입력해보자. 

package org.opentutorials.javatutorials.condition;

public class LoginDemo {
    public static void main(String[] args) {
    	String id = args[0];
		if(id.equals("egoing")){
			System.out.println("right");
		} else {
			System.out.println("wrong");
		}
	}
}

위의 프로그램을 실행하기 위해서는 조금 새로운 방법을 사용해야 한다. 파일을 컴파일한 후에 실행할 때 아래와 같이 입력한다.

java LoginDemo egoing

egoing은 Java 앱인 LoginDemo의 입력 값이다. 이 값은 프로그램 내부로 전달된다. 그럼 프로그램에서 이 값을 알아내는 구문은 아래와 같다.

String id = args[0];

우린 아직 배열을 배우지 않았다. 따라서 위의 코드가 무엇인지 정확하게 설명하는 것은 지금 단계에서는 불필요하다. args[0]가 첫 번째 입력 값(egoing)을 의미한다고만 이해하자. 위의 코드는 입력 값을 문자열 타입의 변수 id에 담고 있다.

사용자가 입력한 데이터가 egoing과 같은지 비교할 때는 아래와 같이 id.equals("egoing")이라는 구문을 사용한다. equal은 같다는 의미다. 즉 사용자가 입력한 값(id)가 "egoing"인지를 확인하는 것이다. 그 결과가 true라면 right가 출력되고, false라면 wrong가 출력될 것이다.

if(id.equals("egoing")){

조건문의 중첩

위의 예제에서 아이디와 비밀번호를 모두 검증해야 한다면 어떻게 하면 될까? 다음 예제를 보자.

package org.opentutorials.javatutorials.condition;

public class LoginDemo2 {
    public static void main(String[] args) {
		String id = args[0];
		String password = args[1];
		if (id.equals("egoing")) {
			if (password.equals("111111")) {
				System.out.println("right");
			} else {
				System.out.println("wrong");
			}

		} else {
			System.out.println("wrong");
		}
	}
}

이 예제는 입력 값을 두 개 받는다. id와 password를 프로그램 내부로 전달하려면 프로그램을 실행할 때 아래와 같이 차례대로 아이디와 비밀번호를 입력하면 된다.

java LoginDemo2 egoing 111111

if문 안에 다시 if문이 등장했다. 즉 사용자가 입력한 값과 아이디의 값이 일치하는지를 확인한 후에 일치한다면 비밀번호가 일치하는지 확인한 것이다. 이렇게 조건문은 조건문 안에 중첩적으로 사용될 수 있다.

switch 문

조건문의 대표적인 문법은 if문이다. 사용빈도는 적지만 조건이 많다면 switch문이 로직을 보다 명료하게 보여줄 수 있다. 아래의 코드를 보자.

package org.opentutorials.javatutorials.condition;

public class SwitchDemo {

    public static void main(String[] args) {
		
		System.out.println("switch(1)");
		switch(1){
		case 1:
			System.out.println("one");
		case 2:
			System.out.println("two");
		case 3:
			System.out.println("three");
		}
		
		System.out.println("switch(2)");
		switch(2){
		case 1:
			System.out.println("one");
		case 2:
			System.out.println("two");
		case 3:
			System.out.println("three");
		}
		
		System.out.println("switch(3)");
		switch(3){
		case 1:
			System.out.println("one");
		case 2:
			System.out.println("two");
		case 3:
			System.out.println("three");
		}

	}

}

결과는 아래와 같다.

switch(1)
one
two
three
switch(2)
two
three
switch(3)
three

즉 switch 뒤의 괄호에 숫자로 1이 주어지면 case 1에 해당하는 로직 이후의 모든 case들이 실행된다.

아래와 같이 코드를 바꿔보자.

package org.opentutorials.javatutorials.condition;

public class SwitchDemo {

    public static void main(String[] args) {
		
		System.out.println("switch(1)");
		switch(1){
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3:
			System.out.println("three");
			break;
		}
		
		System.out.println("switch(2)");
		switch(2){
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3:
			System.out.println("three");
			break;
		}
		
		System.out.println("switch(3)");
		switch(3){
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3:
			System.out.println("three");
			break;
		}

	}

}

결과는 다음과 같다.

switch(1)
one
switch(2)
two
switch(3)
three

break를 만나면 switch 문의 실행이 즉시 중지된다. 따라서 위의 코드는 아래와 같이 if문으로 변경 할 수 있다.

package org.opentutorials.javatutorials.condition;

public class SwitchDemo2 {

    public static void main(String[] args) {
		
		int val = 1;
		if(val == 1){
			System.out.println("one");
		} else if(val == 2){
			System.out.println("two");
		} else if(val == 2){
			System.out.println("three");
		}

	}

}

 즉 if문과 switch문은 서로 대체 가능한 관계다. 이번에는 default를 알아보자.

package org.opentutorials.javatutorials.condition;

public class SwitchDemo {

    public static void main(String[] args) {
		
		System.out.println("switch(1)");
		switch(1){
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3:
			System.out.println("three");
			break;
		default:
			System.out.println("default");
			break;
		}
		
		System.out.println("switch(2)");
		switch(2){
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3:
			System.out.println("three");
			break;
		default:
			System.out.println("default");
			break;
		}
		
		System.out.println("switch(3)");
		switch(3){
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3:
			System.out.println("three");
			break;
		default:
			System.out.println("default");
			break;
		}
		
		System.out.println("switch(4)");
		switch(4){
		case 1:
			System.out.println("one");
			break;
		case 2:
			System.out.println("two");
			break;
		case 3:
			System.out.println("three");
			break;
		default:
			System.out.println("default");
			break;
		}

	}

}

위의 코드는 각 switch 문에 default:가 이끄는 구문을 추가했다. 그 결과는 아래와 같다.

switch(1)
one
switch(2)
two
switch(3)
three
switch(4)
default

가장 마지막은 default로 끝난다. 즉 주어진 케이스가 없는 경우 default 문이 실행된다는 것을 알 수 있다. 

switch 문을 사용할 때 한가지 주의 할 것은 switch의 조건으로는 몇가지 제한된 데이터 타입만을 사용할 수 있다. byte, short, char, int, enum, String, Character, Byte, Short, Integer

이렇게 해서 제대로 된 프로그램의 꼴을 갖춘 것을 한번 만들어봤다. 조건문까지 왔다면 고지가 얼마 남지 않았다. 조금만 힘내자.

Designed by factor[e] design initiative

댓글

댓글 본문
  1. 24.01.11 완료
  2. 모멋
    23.07.09 학습 완료.
  3. 오늘도긍정적으로
    2023년 06월 12일 월요일 학습완료!
  4. 서달
    20230309
  5. 완료
  6. coster97
    .
  7. wwwqiqi
    완료
  8. 코딩드림
    221120
  9. 혜봉
    9/14 완료
  10. 하앙
    완료
  11. 람보
    2022.8.19
  12. 잠룡
    String id = args[0];
    String password = args[1];
    if (id.equals("egoing")) {
    if (password.equals("1234")) {
    System.out.println("Access");
    } else {
    System.out.println("Unable to Access");
    }
    } else {
    System.out.println("ID is wrong");
    }
    제가 이해하기론 위에서 run configuration -> argument를 통해
    id를 틀리게 입력을 하면 패스워드를 입력하지 않아도
    if문을 실행하지 않고 바로 else로 이동해 ID is wrong를 출력이 되어야 하는 것이 아닌가요?
    저는 id만 틀리게 적고 출력을 하면 에러가 뜨고 패스워드까지 적어야 ID is wrong이 출력되는데
    어디서 잘 못 된걸까요?
    출력란의 에러메세지는
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1
    at org.opentutorials.javatutorials.condition.Login2Demo.main(Login2Demo.java:7)
    이렇게 나옵니다
  13. 치키티타
    220617
  14. 20220424
  15. 김은희
    20220403 완료
    조건문 중첩 다시보기
    switch도 복습하기
    val 이 뭔지?
    if문과 switch문은 대체가능한 관계이다
  16. 작심삼일
    2022.02.24
    듣고 보기만 하지않고 직접 코딩? 작성하여
    이해를 가져보려고 노력하였다
    역시 직접 하나하나 해보는게 최고다
  17. 민둥빈둥
    22.01.25
  18. 모찌말랑카우
    22.01.24 완료
  19. 생동태
    2022.01.14 완료
  20. 구니
    22.01.06 완료
  21. syh712
    2021-11-25
    11:05-45 자바강의 <조건문1,2,3,4,5>
    1. if(true or false) { ... }
    이프절이 참이면, 덴절이 실행
    이프절이 거짓이면, 덴절은 실행X

    2. else
    if (true) {*} else {}
    if (false) {} else {*}
    if (false) else if(true} {* } else { }
    if (false) else if(false) { } else {* }
    *else if 는 복수개로 사용가능

    3. 응용- 조건문을 활용한 로그인 프로그램의 코드예시
    *소비자일때보다 생산자가 됐을 때 귀한 게 늘어가는 즐거움이 중요하다.

    public class LoginDemo {
    public static void main(String[] args) {
    String id = args[0];
    if(id.equals("egoing")){
    System.out.println("right");
    } else {
    System.out.println("wrong");
    }
    }
    }

    4. 조건문 중첩 - 아이디와 비밀번호를 모두 검증시
    public class LoginDemo2 {
    public static void main(String[] args) {
    String id = args[0];
    String password = args[1];
    if (id.equals("egoing")) {
    if (password.equals("111111")) {
    System.out.println("right");
    } else {
    System.out.println("wrong");
    }

    } else {
    System.out.println("wrong");
    }
    }
    }


    5. switch 문
    f문과 switch문은 서로 대체 가능한 관계. 그러나 스위치문이 더 명료.
    (1)스위치문
    switch(1){
    case 1:
    System.out.println("one");
    break;
    case 2:
    System.out.println("two");
    break;
    case 3:
    System.out.println("three");
    break;
    default:
    System.out.println("default");
    break;
    }
    *디폴트: 주어진 케이스에 해당되지 않는 경우 디폴트에 지정된 값으로 반환.
    (2) 이프문
    int val = 1;
    if(val == 1){
    System.out.println("one");
    } else if(val == 2){
    System.out.println("two");
    } else if(val == 2){
    System.out.println("three");
    }
  22. 네제가해냈습니다
    211114
  23. 드림보이
    2021.11.11. 조건문 파트 수강완료
  24. IaaS
    package src;

    public class test2{

    public static void main(String[] args) {

    System.out.println("조건문 : IF의 사용법");

    if(true) {
    System.out.println("result : true"); //
    }


    else {

    System.out.println("그 외의 경우");
    }

    }

    }
    2021.10.25 수강완료
    강사님이 준비해주신 자료대로 코드를 입력해보고 실력하면 왼쪽 줄에 DEAT CODE라는 느낌표가 나온다.

    DEAD CODE란 죽은 코드를 의미한다. 다시말하면 굳이 안써도 되는 코드라는 뜻이다.
    else문은 현재의 코드에서는 컴퓨터의 자원만 먹을 뿐 굳이 안써도 되는 코드이다.
    왜냐하면 if 조건안에 true값을 지정했으므로 else까지 결코 넘어 가지 않기 때문이다.

    반대로 if(false)를 넣고 else를 쓰면 if문 옆에 Dead code라는 느낌표가 뜨는것을 확인 할 수가 있다.
  25. 안젤라비
    21-10-21 THU
  26. 성치
    2021-10-21일 완료
  27. H4PPY
    1010
  28. 미NI언
    10.7 완료
  29. 아하
    21.09.28 완료
  30. 하성호
    210903
  31. 베이스박
    210823 학습했습니다. 감사합니다.
  32. 오션멍키
    210822
  33. 유찬s
    실행하실때 터미널에서 java org.opentutorials.javatutorials.condition egoing 이라고 하시면 되실 거에요.
    대화보기
    • super1Nova
      210810
    • 이땅콩
      Run config에서 아규먼트에 값을 넣어보셨나요??
      값을 넣지 않으면 배열이 지정되지 않아 아웃 오브 인덱스 나옵니다!
      대화보기
      • B=loom
        2021.07.19
      • 악어수장
        5.11 2회독 완료
      • 개발꾸꾸
        5.10
      • 댕댕댕
        저도 똑같이 뜨는 걸 보니, 특별히 잘못된 부분은 없는 것 같네요.
        해당 예제는 args[0], 즉 입력값을 필요로 하는 조건문입니다. 그래서 run configurations의 argument에 입력값을 입력하여 실행해야 해당되는 출력값이 출력됩니다.

        자세한 건 해당 동영상을 보시면 나옵니다.
        대화보기
        • 드림보이
          수강완료했습니다...
        • Ruinark
          21.03.18 완료
        • 새긑
          응용 3번째 예제에
          package org.opentutorials.javatutorials.condition;

          public class LoginDemo {

          public static void main(String[] args) {
          String id = args[0];
          if (id.equals("egoing")) {
          System.out.println("right");
          } else {
          System.out.println("wrong");
          }
          }
          }

          이대로 썼는데 자꾸 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
          at org.opentutorials.javatutorials.condition.LoginDemo.main(LoginDemo.java:6)
          이렇게 에러가 나네요. 배열이랑 인덱스에 오류가 있는 것 같은데 어떻게 해야할지 모르겠어요
        • 김청수
          210227 토 완료
        • 하연주
          210202 완료
        • neverdie
          중요챕터
        • Newlife
          간단하게 로그인 하는 방법을 응용해보았다.
          아이디를 정상적으로 입력해야만 비밀번호를 입력할 수 있도록 수정했다.

          아이디 입력요구
          - 정상 : 비밀번호 입력요구
          - 실패 : 아이디 올바르지 않음.

          비밀번호 입력요구
          - 정상 : 로그인 완료
          - 실패 : 비밀번호 올바르지 않음.

          import javax.swing.JOptionPane;

          public class PracticeTest {

          public static void main(String[] args){

          String id = JOptionPane.showInputDialog("ID를 입력하시오.");
          //String pw = JOptionPane.showInputDialog("P/W를 입력하시오.");

          if(id.equals("ID")) {
          String pw = JOptionPane.showInputDialog("P/W를 입력하시오.");
          if(pw.equals("PW")) {
          System.out.println("로그인 완료.");
          }else {
          System.out.println("P/W가 올바르지 않습니다.");
          }
          }else {
          System.out.println("ID가 올바르지 않습니다.");
          }
          }
          }
        • 김민혁
          21/1/9 오늘은 여기까지~!
        • 박소영
          최고
        • 코린이
          202011.20 학습 완료
        • 배우는중
          저도 처음에 꼭 필요한 구문인 줄 알았는데 생략해도 출력이 잘 되더군요. 제가 보기에도 콘솔에 출력했을 때 배우시는 분들이 보기 쉽게 구분하기 위한 용도로 써둔 것 같습니다.

          애초에 System.out.println("swich(숫자)") 뒤에 따로 중괄호가 쓰이지 않은 걸로 보아 하나의 문법적인 틀로 쓰이기 보단

          [console]
          swich(숫자) <- System.out.println("swich(숫자)")
          one
          two
          three

          이처럼 콘솔에 출력하였을 때 영상 보시는 분들이 잘 구분하여 볼 수 있게끔 써둔 것 같습니다.
          대화보기
          버전 관리
          egoing
          현재 버전
          선택 버전
          graphittie 자세히 보기