조건문 형식
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);
}
System.out.println("b");
}
}
참고) equals vs ==
public class Equals {
public static void main(String[] args) {
int p1 = 1;
int p2 = 1;
boolean a = p1 == p2;
System.out.println("a: " + a);
String o1 = new String("java");
String o2 = new String("java");
boolean b = o1 == o2;
System.out.println("b: " + b);
String o3 = "java2";
String o4 = "java2";
boolean c = o3 == o4 ;
System.out.println("c: "+c);
}
}
조건문 응용1
- if (inputId == id) --> 이거 안됨.
- 대신 if ( inputId.equals(id) )
public class AuthApp {
public static void main(String[] args) {
String id = "egoing";
String inputId = args[0];
System.out.println("Hi.");
if(inputId.equals(id)) {
System.out.println("Master!");
} else {
System.out.println("Who are you?");
}
}
}
조건문 응용 2
import java.util.Scanner;
public class AuthApp {
public static void main(String[] args) {
String id = "hyun" ;
Scanner in = new Scanner (System.in) ;
System.out.print("Id?: ");
String inputId = in.next() ;
String pass = "1111" ;
System.out.print("password?: ");
String inputPass = in.next() ;
if ( inputId.equals(id) && inputPass.equals(pass) ) {
System.out.println("Hi! " + inputId );
} else {
System.out.println("WRONG ID or PASSWORD!");
}