조건문 + 불린 => 비교
if
if(true/false){ //if절
} //then절
package org.opentutorials.javatutorials.condition;
public class ConditionDemo2 {
public static void main(String[] args) {
if(false) {
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
}
System.out.println(5);
}
}
//5
else 절
if(true/false){
} else {
}
package org.opentutorials.javatutorials.condition;
public class ConditionDemo3 {
public static void main(String[] args) {
if(false) {
System.out.println(1);
} else {
System.out.println(2);
}
}
}
//2
else if
복수 사용가능
if(true/false){
} else if(true/false) {
} else {
}
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);
}
}
}
//2 => 첫번째 true에서 if문 탈출
변수, 비교연산자, 조건문 조합
package org.opentutorials.javatutorials.condition;
public class LoginDemo {
public static void main(String[] args) {
String id = args[0]; //입력값
if(id.equals("egoing")) { //arg[0] 입력값을 id에 대입
System.out.println("right");
} else {
System.out.println("wrong");
}
}
}
& run configuration- arguments 에 입력값 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("1111111")) {
System.out.println("right");
} else {
System.out.println("wrong");
}
}
}
}
switch
사용빈도 적지만 조건 많을 시 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");
}
}
}
=> switch(1) -> case 1,2,3 실행
=> switch(2) -> case 2,3 실행
=> switch(3) -> case 3 실행
- switch문과 일치하는 조건만 실행하고 싶을 때 : break
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
package org.opentutorials.javatutorials.condition;
public class SwitchDemo {
public static void main(String[] args) {
System.out.println("switch(1)");
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"); //default
}
}
}
=> switch구문 조건에 없는 숫자 입력하면 디폴트값 출력함
- switch 구문 조건 (한정된 데이터 타입)
byte, short, char, int, enum, String, Character, Byte, Short, Integer
'Programming > 자바' 카테고리의 다른 글
생활코딩 자바 - 반복문 (0) | 2022.03.14 |
---|---|
생활코딩 자바 - 논리연산자 (0) | 2022.03.13 |
생활코딩 자바 - 비교와 Boolean (0) | 2022.03.13 |
생활코딩 자바 - 연산자 (0) | 2022.03.12 |
생활코딩 자바 - 형변환 (0) | 2022.03.04 |