[java실습문제] 조건문 if, switch
문제1
public void practice1() {
// 아래 예시와 같이 메뉴를 출력하고 메뉴 번호를 누르면 “OO메뉴입니다“를,
// 종료 번호를 누르면 “프로그램이 종료됩니다.”를 출력하세요.
int menu = 0;
String str = "";
Scanner scanner = new Scanner(System.in);
System.out.println("1. 입력");
System.out.println("2. 수정");
System.out.println("3. 조회");
System.out.println("4. 삭제");
System.out.println("9. 종료");
System.out.print("메뉴 번호를 입력하세요 : ");
menu = scanner.nextInt();
switch(menu) {
case 1 :
str = "입력";
break;
case 2 :
str = "수정";
break;
case 3 :
str = "조회";
break;
case 4 :
str = "삭제";
break;
case 9 :
System.out.println("프로그램이 종료됩니다.");
return;
}
<switch문>
[표현법]
switch (조건식) {
case 값1 :
.. 실행 코드1 ..;
break;
case 값2 :
.. 실행 코드2 ..;
break;
default
위 조건을 모두 만족하지 않을 경우 실행하게 될 코드
}
- switch 문은 if문처럼 조건식이 true일 경우에 실행문을 실행하는 것이 아니라, 조건식의 결과 값(정수, 문자, 문자열) 에 따라 실행문이 선택된다.
- if 문과 다르게 실행 코드를 실행하고 자동으로 빠져나가지 못한다. (break가 필요하다.)
문제2
public void practice2() {
// 키보드로 정수를 입력 받은 정수가 양수이면서 짝수일 때만 “짝수다”를 출력하고
// 짝수가 아니면 “홀수다“를 출력하세요.
// 양수가 아니면 “양수만 입력해주세요.”를 출력하세요.
int num = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("숫자를 한 개 입력하세요 : ");
num = scanner.nextInt();
// if (num < 0) {
// System.out.println("양수만 입력해주세요");
// } else if (num % 2 ==0 && num > 0) {
// System.out.println("짝수다");
// } else if (num % 2 != 0 && num > 0) {
// System.out.println("홀수다");
// }
if(num > 0) {
if(num % 2 == 0) {
System.out.println("짝수다.");
} else {
System.out.println("홀수다.");
}
} else {
System.out.println("양수만 입력해주세요.");
}
}
내가 쓴 코드와 강사님 코드 비교..
전체 조건을 0이상, 그안에서 짝수이면 "짝수다", 아니면 "홀수다", 전체 조건이 아니면 "양수만 입력해주세요"
(이렇게도 저렇게도 할수 있구나~~~ 많이 해봐야 겠다~~ )
문제3
public void practice3() {
// 국어, 영어, 수학 세 과목의 점수를 키보드로 입력 받고 합계와 평균을 계산하고
// 합계와 평균을 이용하여 합격 / 불합격 처리하는 기능을 구현하세요.
// (합격 조건 : 세 과목의 점수가 각각 40점 이상이면서 평균이 60점 이상일 경우)
// 합격 했을 경우 과목 별 점수와 합계, 평균, “축하합니다, 합격입니다!”를 출력하고
// 불합격인 경우에는 “불합격입니다.”를 출력하세요.
int langScore = 0;
int mathScore = 0;
int engScore = 0;
int sum = 0;
double avg = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("국어점수 : ");
langScore = scanner.nextInt();
System.out.print("수학점수 : ");
mathScore = scanner.nextInt();
System.out.print("영어점수 : ");
engScore = scanner.nextInt();
sum = langScore + engScore + mathScore;
avg = sum/3;
if (langScore >= 40 && engScore >= 40 && mathScore >= 0 && avg >= 60) {
System.out.println("국어 : " + langScore + "\n수학 : " + mathScore + "\n영어 :" + engScore + "\n합계 : " + sum + "\n평균 : " + avg + "\n축하합니다. 합격입니다!");
} else {
System.out.println("불합격입니다.");
}
}
문제4
public void practice4() {
// 수업 자료(7page)에서 if문으로 되어있는 봄, 여름, 가을, 겨울 예제를 switch문으로 바꿔서 출력하세요.
int month = 0;
String season = "";
Scanner scanner = new Scanner(System.in);
System.out.println("1~12 사이의 정수 입력 : ");
month = scanner.nextInt();
switch (month) {
case 3 :
case 4 :
case 5 :
season = "봄";
break;
case 6 :
case 7 :
case 8 :
season = "여름";
break;
case 9 :
case 10 :
case 11 :
season = "가을";
break;
case 12 :
case 1 :
case 2 :
season = "겨울";
break;
default :
season = "잘못 입력된 달";
break;
}
}
switch 변수설정, 조건문 설정 잘 설정하자.!
문제5
public void practice5() {
// 아이디, 비밀번호를 정해두고 로그인 기능을 작성하세요.
// 로그인 성공 시 “로그인 성공”,
// 아이디가 틀렸을 시 “아이디가 틀렸습니다.“,
// 비밀번호가 틀렸을 시 “비밀번호가 틀렸습니다.”를 출력하세요.
String inputId = "";
String inputPw = "";
String userId = "ismoon";
String userPw = "1234";
Scanner scanner = new Scanner(System.in);
System.out.print("아이디 : ");
inputId = scanner.nextLine();
System.out.print("비밀번호 : ");
inputPw = scanner.nextLine();
if(userId.equals(inputId) && userPw.equals(inputPw)) {
System.out.println("로그인 성공");
} else if(userId.equals(inputId)) {
System.out.println("비밀번호가 틀렸습니다.");
} else if(userPw.equals(inputPw)) {
System.out.println("아이디가 틀렸습니다.");
} else {
System.out.println("모두 틀렸습니다.");
}
}
String(문자열)의 비교는 '==' 사용 불가!!! .equals( )사용!
문제6
중복된 출력문과 조건이 true,false가 아닌 값이 나오기 때문에 switch문 사용해야함
수정
public void practice6() {
// 사용자에게 관리자, 회원, 비회원 중 하나를 입력 받아 각 등급이 행할 수 있는 권한을 출력하세요.
// 단, 관리자는 회원관리, 게시글 관리, 게시글 작성, 게시글 조회, 댓글 작성이 가능하고
// 회원은 게시글 작성, 게시글 조회, 댓글 작성이 가능하고
// 비회원은 게시글 조회만 가능합니다.
// (단, 잘못 입력하였을 경우 “잘못 입력했습니다.” 라는 출력문이 출력되도록)
Scanner scanner = new Scanner(System.in);
System.out.print("권한을 확인하고자 하는 회원 등급 : ");
switch (scanner.nextLine()) {
case "관리자" :
System.out.println("회원관리, 게시글 관리");
case "회원" :
System.out.println("게시글 작성, 댓글 작성");
case "비회원 :" :
System.out.println("게시글 조회");
break;
default :
System.out.println("잘못 입력하셨습니다.");
break;
}
}
switch (scanner.nextLine()) // 사용자 입력을 읽어와서 바로 비교할 수 있다.
문제7
public void practice7() {
// 메소드 명 : public void practice7(){}
// 키, 몸무게를 double로 입력 받고 BMI지수를 계산하여 계산 결과에 따라
// 저체중 / 정상체중 / 과체중 / 비만을 출력하세요.
// BMI = 몸무게 / (키(m) * 키(m))
// BMI가 18.5미만일 경우 저체중 / 18.5이상 23미만일 경우 정상체중
// BMI가 23이상 25미만일 경우 과체중 / 25이상 30미만일 경우 비만
// BMI가 30이상일 경우 고도 비만
double height = 0;
double weight = 0;
double bmi = 0;
Scanner scanner = new Scanner(System.in);
bmi = weight / (height * height);
System.out.print("키(m)를 입력해 주세요 : ");
height = scanner.nextDouble();
System.out.print("몸무게(kg)를 입력해 주세요 : ");
weight = scanner.nextDouble();
System.out.println("BMI 지수 : " + bmi);
if (bmi < 18.5) {
System.out.println("저체중");
} else if (bmi >= 18.5 && bmi < 23) {
System.out.println("정상체중");
} else if (bmi >= 23 && bmi < 25) {
System.out.println("과체중");
} else if (bmi >= 25 && bmi < 30) {
System.out.println("비만");
} else {
System.out.println("고도 비만");
}
}
문제8
public void practice8() {
// 키보드로 두 개의 양수와 연산 기호를 입력 받아 연산 기호에 맞춰 연산 결과를 출력하세요.
// (단, 양수가 아닌 값을 입력하거나 제시되어 있지 않은 연산 기호를 입력 했을 시
// “잘못 입력하셨습니다. 프로그램을 종료합니다.” 출력)
// (printf()문을 이용하여 마지막 출력문을 작성해보시오.)
int num1 = 0;
int num2 = 0;
int result = 0;
char op = '\u0000';
Scanner scanner = new Scanner(System.in);
System.out.print("피연산자1 입력 : ");
num1 = scanner.nextInt();
System.out.print("피연산자2 입력 : ");
num2 = scanner.nextInt();
scanner.nextLine();
System.out.print("연산자 입력(+,-,*,/,%) : ");
op = scanner.nextLine().charAt(0);
if (num1 > 0 && num2 >0) {
switch (op) {
case '+' :
result = num1 + num2;
break;
case '-' :
result = num1 - num2;
break;
case '*' :
result = num1 * num2;
break;
case '/' :
result = num1 / num2;
break;
case '%' :
result = num1 % num2;
break;
default :
System.out.println("연산자를 잘못 입력하셨습니다. 프로그램을 종료합니다.");
return;
}
} else {
System.out.println("양수가 아닌 값을 입력하셨습니다. 프로그램을 종료합니다.");
}
System.out.printf("%d %c %d = %d", num1, op, num2, result);
}
문제9
public void practice9() {
// 중간고사, 기말고사, 과제점수, 출석회수를 입력하고 Pass 또는 Fail을 출력하세요.
// 총 점 100점 중 배점으로는 다음과 같다.
// 중간고사 (20%), 기말고사 (30%), 과제 (30%), 출석 (20%)
// 이 때, 출석 회수는 총 강의 회수 20회 중에서 출석한 날만 입력
// 총 점이 70점 이상이면서 전체 강의의 70%이상 출석을 했을 경우 Pass, 아니면 Fail을 출력하세요.
double mTest = 0;
double fTest = 0;
double project = 0;
double attend = 0;
double total = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("중간 고사 점수 : ");
mTest = scanner.nextInt() * 0.2;
System.out.print("기말 고사 점수 : ");
fTest = scanner.nextInt() * 0.3;
System.out.print("과제 점수 : ");
project = scanner.nextInt() * 0.3;
System.out.print("출석 횟수 : ");
attend = scanner.nextInt();
total = mTest + fTest + project + attend;
System.out.println("=========결과=========");
if (total >= 70 && attend >= 14) {
System.out.println("중간 고사 점수(20) :" + mTest);
System.out.println("기말 고사 점수(30) :" + fTest);
System.out.println("과제 점수(30) :" + project);
System.out.println("출석 점수(20) :" + attend);
System.out.println("총점 :" + total);
System.out.println("PASS");
} else {
if (attend < 14) {
System.out.println("FAIL [출석 횟수 부족] (" + (int)attend +"/20)");
}
if (total < 70) {
System.out.println("FAIL [점수미달] (총점" + total +")");
}
}
}
문제10
public void practice10() {
// 앞에 구현한 실습문제를 선택하여 실행할 수 있는 메뉴화면을 구현하세요.
int menu = 0;
Scanner sc = new Scanner(System.in);
System.out.println("실행할 기능을 선택하세요.");
System.out.println("1. 메뉴 출력");
System.out.println("2. 짝수/홀수");
System.out.println("3. 합격/불합격");
System.out.println("4. 계절");
System.out.println("5. 로그인");
System.out.println("6. 권한 확인");
System.out.println("7. BMI");
System.out.println("8. 계산기");
System.out.println("9. Pass/Fail");
System.out.print("선택 : ");
menu = sc.nextInt();
switch (menu) {
case 1:
practice1();
break;
case 2:
practice2();
break;
case 3:
practice3();
break;
case 4:
practice4();
break;
case 5:
practice5();
break;
case 6:
practice6();
break;
case 7:
practice7();
break;
case 8:
practice8();
break;
case 9:
practice9();
break;
default :
System.out.println("잘못 입력하였습니다.");
}
}
- switch 실행문에 메소드 입력