-
3일 차 JAVA switch문과 if문의 활용 구분하기삼성SDS_멀티캠퍼스/Java 2015. 9. 9. 14:41반응형
switch문과 if문의 차이점을 알아보기 위해
간단한 코드를 작성해 보았다.
switch문
소스코드
-------------------------
import java.util.Scanner;
public class Test11 {
public static void main(String arg[]) {
int score;
int random_value;
Scanner scan = new Scanner(System.in);
System.out.println("1~10사이의 점수를 입력하세요");
score = scan.nextInt();
random_value = (int) (Math.random() * score);
switch (random_value) {
case 1:
System.out.println("Bananas");
break;
case 2:
System.out.println("Oranges");
break;
case 3:
System.out.println("Pears");
case 4:
System.out.println("Apples");
case 5:
System.out.println("Plums");
break;
case 6:
System.out.println("Pineapples");
break;
case 7:
break;
default:
System.out.println("Nuts");
break;
}
}
}
if문
소스코드
-------------------------
import java.util.Scanner;
import javax.print.attribute.standard.Finishings;
public class Test12 {
public static void main(String arg[]) {
int score;
int random_value;
Scanner scan = new Scanner(System.in);
System.out.println("1~10사이의 점수를 입력하세요");
score = scan.nextInt();
random_value = (int) (Math.random() * score);
if (random_value == 1) {
System.out.println("Bananas");
} else if (random_value == 2) {
System.out.println("Oranges");
} else if (random_value == 3) {
System.out.println("Pears");
System.out.println("Apples");
System.out.println("Plums");
} else if (random_value == 4) {
System.out.println("Pears");
System.out.println("Apples");
} else if (random_value == 5) {
System.out.println("Pears");
} else if (random_value == 6) {
System.out.println("Pineapples");
} else if (random_value == 7) {
} else {
System.out.println("Nuts");
}
}
}
경우에 따라 switch문이 더 짧게 쓰일 수도 있다출처: 삼성SDS멀티캠퍼스
강사: 홍승길
Email : iccack70@gmail.com
반응형'삼성SDS_멀티캠퍼스 > Java' 카테고리의 다른 글
3일 차 JAVA 중간점검 (정수 입력받아서 평균을 출력, 천, 백, 십, 일의 자리로 분리하여 출력 / 숫자를 시, 분, 초로 변환, 구구단) (0) 2015.09.09 3일 차 JAVA while문을 이용하여 입력받은 숫자를 구구단으로 출력 (0) 2015.09.09 3일 차 JAVA switch문을 이용하여 학점계산기 만들기 (1) 2015.09.09 3일 차 JAVA switch문을 이용하여 월의 일수 계산하기 (0) 2015.09.09 3일 차 JAVA random() 함수를 이용하여 간단한 게임만들기 (0) 2015.09.09