2016년 7월 19일 화요일

Java 1-4 제어문 if ,switch,case, 부르마블 주사위


public class If {

public static void main(String[] args) {

int num = 99;
if (num > 15) {
System.out.println("15초과");
}
// if {} else {}
// if {} else if (조건) {} 형태도 가능
else {
System.out.println("15이하");
}


}

}
//부르마블 주사위 던지기
public class IfEx1 {

public static void main(String[] args) {

System.out.println("주사위를 던집니다. 더블이 나오면 다시 던질 수 있습니다.");
//이동거리 정의
int distance = 0;
//무한반복
while (true) {
// 꿀팁 : 특정부분을 밀고싶으면(tab) 블록지정하고 tab누르면 된다.
// dice1,2는 랜덤 주사위값
int dice1 = (int) (Math.random() * 6) + 1;
int dice2 = (int) (Math.random() * 6) + 1;
distance = distance + dice1 + dice2;
if (dice1 == dice2) {
System.out.println("꺄! 더블"+dice1+"이(가) 나왔네요!");
System.out.println("다시 한번 던집니다.");

   } else {
System.out.println(dice1 + ", " + dice2 + " 눈금이 나왔어요.");
break;
}
}
System.out.println("총 이동거리는 "+ distance + "입니다.");

}

}

public class IfEx2 {

public static void main(String[] args) {
// 학점별 분기 코드
float score = 87.5F;
if (score >= 90) {
System.out.println("A학점");
}
//else를 사용하면 앞에서 나온 if의 조건을 제외한 나머지 조건만 적으면 된다.
else if (score >= 80) {
System.out.println("B학점");
}
else if (score >= 70) {
System.out.println("C학점");
}
else if (score >= 60) {
System.out.println("D학점");
}

}

}

public class Switch {

public static void main(String[] args) {

// switch은 조건이 아닌 값 하나를 가지고 분기를 하는 분기문.
int menuCode = 2;
switch (menuCode) {
case 1:
System.out.println("1번 기능");
break;
case 2:
System.out.println("2번 기능");
case 3:
System.out.println("3번 기능");
break;
case 4:
case 5:
System.out.println("4번/5번 기능");
break;
default:
System.out.println("잘못 선택한 기능입니다.");
break;
}
// 값이 1일때 : 1번 기능 수행
// 값이 2일때 : 2번 기능 수행 후 3번 기능 수행
// 값이 3일때 : 3번 기능 수행
// 값이 4일때 : 4/5번 기능 수행
// 값이 5일때 : 4/5번 기능 수행
// 값이 그 외의 값일때 : 잘못 선택한 기능이라고 출력
// 위의 코드를 if문으로 전환하세요
// 5개의 println구문은 더 이상 추가하지 말고, 변경하지 말것 
// 왜?? >> 같은 구문을 복사함으로 복수개 존재하면 유지보수가 어렵다.
// default 구문은 필히 else 구문으로 사용할 것(else if도 사용하지 말라)
// default 구문을 else만으로 처리하기 위해 그에 해당하는 반대조건을 모두 한번에 쓰지 말것
// 왜?? >> 마지막 else는 조건을 안 붙이는 편이 에러를 줄일 수 있다.
if (menuCode == 1) {
System.out.println("1번 기능");
}
else if (menuCode == 2 || menuCode == 3) {

if (menuCode ==2) {
System.out.println("2번 기능");
}
System.out.println("3번 기능");
}
else if (menuCode == 4 || menuCode == 5 ) {
System.out.println("4번/5번 기능");
}
else {
System.out.println("잘못 선택한 기능입니다.");
}
}

}

댓글 없음:

댓글 쓰기