반응형
- if ~ else 사용
public class IfExam2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(">>점수 입력 ");
int score = scanner.nextInt();
ifElseTest(score);
}
private static void ifElseTest(int score) {
if(score >= 90) {
System.out.println("90이상");
System.out.println("A");
} else {
System.out.println("90미만");
System.out.println("B");
}
}
}
보기와 같은 코드일경우 else를 빼고 if문 안에 return; 으로 종료 시키는 코드가 낫다
private static void ifElseTest(int score) {
if(score >= 90) {
System.out.println("90이상");
System.out.println("A");
return;
}
System.out.println("90미만");
System.out.println("B");
}
- else if 사용
public class IfExam3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(">>점수 입력 : ");
int score = scanner.nextInt();
if(score >= 90) {
System.out.println("90점 이상");
} else if (score >= 80) {
System.out.println("80점 이상 90점 미만");
} else if (score >= 70) {
System.out.println("70점 이상 80점 미만");
} else {
System.out.println("70점 미만");
}
}
}
- Math.random() 메소드
- 0과 1사이의 임의의 수 생성 (0을 포함하며 1은 포함되지 않는다.)
- 반환타입은 double이다.
public class MathExam {
public static void main(String[] args) {
double random = Math.random();
// 0 <= random <1 실수값 출력
System.out.println("0과 1사이 난수(0포함): " + random);
// 1~10까지 정수값
int num = (int) (Math.random() * 10 + 1);
System.out.println("1~10까지의 정수 값 : " + num);
// 주사위 : 1~6까지 정수값
int dice = (int) (Math.random() * 6) + 1;
System.out.println("주사위 눈 : " + dice);
// 로또 : 1~45까지 정수값
int lotto = (int) (Math.random() * 45) + 1;
System.out.println("로또 번호 : " + lotto);
}
}
Math.random은 0을 포함하기따문에 1~6번을 표기할려면
Math.radom() 뒤에 1을 더하는 이유는 0부터 시작하기때문.
ex. dice를 예로 본다면 Math.radom() * 6 + 1 -------> (0 1 2 3 4 5 + 1 ) 의 형태다.
- 중첩 if문 제거(삼항 연산자 이용)
public class IfNestedExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print(">>점수 입력 : ");
int score = scanner.nextInt();
String grade = null;
if(score >= 90) {
// if(score >= 95) {
// grade = "A+";
// } else {
// grade = "A";
// }
grade = (score >= 95) ? "A+" : "A"; // 중첩if 제거 코드
} else {
grade = (score >= 85) ? "B+" : "B";
}
System.out.println(grade);
}
}
- switch문
public class SwitchExample {
public static void main(String[] args) {
int num = (int)(Math.random() * 6) + 1;
switch (num) {
case 1:
System.out.println("1의 눈이 나옴");
break;
case 2:
System.out.println("2의 눈이 나옴");
break;
case 3:
System.out.println("3의 눈이 나옴");
break;
case 4:
System.out.println("4의 눈이 나옴");
break;
case 5:
System.out.println("5의 눈이 나옴");
break;
default:
System.out.println("6의 눈이 나옴");
break;
}
}
}
break; 를 넣지 않으면 다음 줄이 이어서 나옴.
반응형
댓글