부스트코스 생활코딩 [쉽게 배우는 자바2] 공부 기록
2-4.1 조건문 형식 (Conditional Statement)
package javaChapter2_4;
public class IfApp {
public static void main(String[] args) {
System.out.println("a");
// if (false) {
// System.out.println(1);
// } else {
// if (true) {
// System.out.println(2);
// } else {
// System.out.println(3);
// }
// }
if (false) {
System.out.println(1);
} else if (true) {
System.out.println(2);
} else {
System.out.println(3);
}
System.out.println("b");
}
}
- if
- else if
- else
조건식에는 boolean 타입만 들어갈 수 있음.
2-4.2 조건문 응용 1
package javaChapter2_4;
import java.util.Scanner;
public class AuthApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input your id: ");
String id = "egoing";
String inputId = sc.next();
System.out.println("Hi");
if (inputId.equals(id)) {
System.out.println("Master!");
} else {
System.out.println("Who are you?");
}
}
}
간단한 인증 기능!
강의에서는 파라미터값을 입력해서 진행했다.
인텔리제이에서는 run-edit configurations 에서 넣을 수 있으나!
나는 scanner 함수 이용해서 작성했다.
eging을 입력했을 때는 master가!
mina를 입력했을 때는 who are you가 출력되는 것을 볼 수 있다.
2-4.3 조건문 응용 2
package javaChapter2_4;
import java.util.Scanner;
public class AuthApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input your id: ");
String id = "egoing";
String inputId = sc.next();
System.out.print("Input your password: ");
String pass = "1111";
String inputPass = sc.next();
System.out.println("Hi");
// if (inputId.equals(id)) {
// if (inputPass.equals(pass)) {
// System.out.println("Master!");
// } else {
// System.out.println("Wrong password");
// }
// } else {
// System.out.println("Who are you?");
// }
if (inputId.equals(id) && inputPass.equals(pass)) {
System.out.println("Master!");
} else {
System.out.println("Who are you?");
}
}
}
비밀번호 확인 기능까지 추가하기!
id랑 password가 다 맞으면 hi master! 라고 뜬다.
id는 맞지만 비밀번호가 틀리면? 또는 아이디가 틀리고 비밀번호만 맞다면?
hi who are you? 라고 뜬다.
id와 password가 다를 때 역시 hi who are you?라고 뜬다.
if (inputId.equals(id)) {
if (inputPass.equals(pass)) {
System.out.println("Master!");
} else {
System.out.println("Wrong password");
}
} else {
System.out.println("Who are you?");
}
조건문을 이렇게 작성할 수도 있으나!
if (inputId.equals(id) && inputPass.equals(pass)) {
System.out.println("Master!");
} else {
System.out.println("Who are you?");
}
논리연산자를 이용해서 이렇게 간단하게도 작성이 가능하다.
300x250
'Language > JAVA' 카테고리의 다른 글
[JAVA] 2-7.1~7.3 반복문 (while, for) 배열 (Array) (0) | 2022.02.04 |
---|---|
[JAVA] 2-5~6 연산자 == , equals 논리연산자 true , false && || (0) | 2022.02.03 |
[JAVA] 2-1~3 Boolean type , false true , 비교연산자 (0) | 2022.02.01 |
[JAVA] 14~15 나의 앱 만들기 (조건문 배열 반복문 메소드 클래스 인스턴스) (0) | 2022.01.31 |
[JAVA] 13 자바 문서 보는 법 - API UI 클래스 인스턴스 상속 (0) | 2022.01.31 |