[Java] 조건문 if/else/elseif/Switch

J.A.Y·2023년 3월 14일
0

Java

목록 보기
3/8

if/if else 조건문을 활용한 로그인 데모 프로그램

public class LoginDemo {
	public static void main(String[] args) {
		String id = args[0];
		String password = args[1];
		if (id.equals("Rara")) {
			if (password.equals("1234")) {
				System.out.println("Right");
			} else {
				System.out.println("Please, check your password.");
			}
		} else {
			System.out.println("Your id and password are wrong");
		}
	}
}
  • Arguments(입력값)에 올바른 id와 잘못된 비밀번호 입력

  • 실행 결과 : 정상 출력

Switch와 if 차이

  • Switch와 if는 같은 조건문이지만 약간의 차이점이 있다. Switch는 true값부터 자동적으로 순차구조로 실행되지만 (별다른 제약을 걸지 않는다면), if와 else, else if는 true인 값만 실행되고 다음 코드는 실행되지 않는다. 이러한 차이점을 유념해서 적절히 사용할 필요가 있다.
public class Variable {
	public static void main(String[] args) {
		System.out.println("Switch(1)");
		switch(2) {
			case 1:
				System.out.println("one"); // 실행X
			case 2:
				System.out.println("two"); //순차구조로 실행
			case 3:
				System.out.println("three"); // 'break'명령어로 'case 3'까지만 실행
				break;
			case 4:
				System.out.println("four");
		}
        
		int a = 1;  
		if (a == 1) {
			System.out.println("one");  // 1출력, 아래 코드들은 실행X
		}
		else if (a == 2) {
			System.out.println("two");
		}
		else if (a == 3) {
			System.out.println("three");
		}
		else if (a == 4) {
			System.out.println("four");
		}
	}
profile
Done is better than perfect🏃‍♀️

0개의 댓글