
public class IfElse {
// 15 : If문 : if () {} else if () {} else {}
static void main(String[] args) {
// if - else if - else
int money = 7900;
if (money >= 8000) {
System.out.println("순대국 배부르다!!!");
} else if (money >= 500) {
System.out.println("계란 후라이 맛있다.");
} else {
System.out.println("돈이 없어요... ㅠㅠ");
}
// if-if중첩
int age = 15;
String gender = "여성";
if (age > 19) {
if (gender.equals("남성")) {
System.out.println("성인 남성");
} else {
System.out.println("성인 여성");
}
} else {
if (gender != "남성") {
System.out.println("미성년 여성");
} else {
System.out.println("미성년 남성");
}
}
}
}
Java의 if문은 JavaScript의 if문과 완전히 똑같이 생겼다.
import java.util.Scanner;
public class SwitchCase {
// 16 : Switch문 switch () { case 값: break; default : }
static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("몇 월인지 입력하세요!");
String monthIn = scanner.nextLine();
int month = Integer.parseInt(monthIn);
switch (month) {
case 1:
System.out.println("January 1월");
break;
case 2:
System.out.println("February 2월");
break;
case 3:
System.out.println("March 3월");
break;
case 4:
System.out.println("April 4월");
break;
case 5:
System.out.println("May 5월");
break;
case 6:
System.out.println("June 6월");
break;
case 7:
System.out.println("July 7월");
break;
case 8:
System.out.println("August 8월");
break;
case 9:
System.out.println("September 9월");
break;
case 10:
System.out.println("October 10월");
break;
case 11:
System.out.println("November 11월");
break;
case 12:
System.out.println("December 12월");
break;
default:
System.out.println("잘못된 값을 입력했습니다.");
// default에는 break 없어도 됨
}
}
}
각 case마다 break;가 꼭 있어야 한다. case에 해당하지 않는 경우는 default에서 받는다. 또한 default에서는 break;가 없어도 된다.