전체 방문자
오늘
어제
21종
종이의 코딩 공부방
21종
  • 분류 전체보기 (171)
    • JAVA (64)
    • Springboot (46)
      • 블로그만들기 (45)
    • Database (60)
      • Oracle (60)
    • 프로젝트 3 (CELOVER) (0)
    • 개발서버 구축 (0)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

인기 글

최근 글

최근 댓글

hELLO · Designed By 정상우.
21종

종이의 코딩 공부방

JAVA

[자바/JAVA] 프로그래밍 - 조건문(if,switch) 실습 예제

2023. 5. 31. 21:10

조건문(if,switch) 예제


문제 01.

아래 예시와 같이 메뉴를 출력하고 메뉴 번호를 누르면 “OO메뉴입니다“를, 종료 번호를 누르면 “프로그램이 종료됩니다.”를 출력하세요.

System.out.println("1. 입력 \n2. 수정 \n3. 조회 \n4. 삭제 \n5. 종료");

Scanner sc = new Scanner(System.in);

System.out.print("메뉴 번호를 입력하세요 : ");
int num = sc.nextInt();

switch(num) {
case 1 :
    System.out.println("입력 메뉴입니다.");
    break;
case 2:
    System.out.println("수정 메뉴입니다.");
    break;
case 3:
    System.out.println("조회 메뉴입니다.");
    break;
case 4:
    System.out.println("삭제 메뉴입니다.");
    break;
default:
    System.out.println("프로그램이 종료됩니다.");
}

sc.close();

문제 02.

키보드로 정수를 입력 받은 정수가 양수이면서 짝수일 때만 “짝수다”를 출력하고 짝수가 아니면 “홀수다“를 출력하세요.
양수가 아니면 “양수만 입력해주세요.”를 출력하세요.

Scanner sc = new Scanner(System.in);

System.out.print("숫자를 한 개 입력하세요 : ");
int num = sc.nextInt();

if(num > 0) {
    if(num % 2 == 0) {
        System.out.println("짝수다");
    }else {
        System.out.println("홀수다");
    }
}else {
    System.out.println("양수만 입력해주세요.");
}
sc.close();

문제 03.

국어, 영어, 수학 세 과목의 점수를 키보드로 입력 받고 합계와 평균을 계산하고 합계와 평균을 이용하여 합격 / 불합격 처리하는 기능을 구현하세요.
(합격 조건 : 세 과목의 점수가 각각 40점 이상이면서 평균이 60점 이상일 경우) 합격 했을 경우 과목 별 점수와 합계, 평균, “축하합니다, 합격입니다!”를 출력하고 불합격인 경우에는 “불합격입니다.”를 출력하세요.

Scanner sc = new Scanner(System.in);

System.out.print("국어점수 : ");
int num1 = sc.nextInt();

System.out.print("수학점수 : ");
int num2 = sc.nextInt();

System.out.print("영어점수 : ");
int num3 = sc.nextInt();

int sum = num1 + num2 + num3;
double avg = (num1 + num2 + num3)/3;
boolean each = (num1 >= 40) && (num2 >= 40) && (num3 >= 40);

if(each && (avg >= 60)) {

    System.out.printf("국어점수 : %d \n수학점수 : %d \n영어점수 : %d ",num1,num2,num3);
    System.out.printf("합계 : %d \n평균 : %f \n축하합니다, 합격입니다!",sum,avg,each);
} else {
    System.out.printf("국어점수 : %d \n수학점수 : %d \n영어점수 : %d \n불합격입니다.",num1,num2,num3);
}
sc.close();

문제 04.

1~12 사이의 정수를 입력받아 봄, 여름, 가을, 겨울 계절을 switch문으로 출력하세요.
**3~5 :봄 / 6~8 : 여름 / 9~11 : 가을 /12~2 : 겨울

Scanner sc = new Scanner(System.in);
System.out.print("1~12 사이의 정수 입력 : ");
int month = sc.nextInt();

String season = "";

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 :
    System.out.println(month + "월은 잘못 입력된 달입니다.");
    sc.close();
    return;
}
System.out.println(month + "월은 " + season + "입니다.");
sc.close();

문제 05.

아이디, 비밀번호를 정해두고 로그인 기능을 작성하세요.
로그인 성공 시 “로그인 성공”,
아이디가 틀렸을 시 “아이디가 틀렸습니다.“,
비밀번호가 틀렸을 시 “비밀번호가 틀렸습니다.”를 출력하세요.

String userId = "myId";
String userPw = "myPassword12";

Scanner sc = new Scanner(System.in);

System.out.print("아이디 : ");
String inputId = sc.nextLine();

System.out.print("비밀번호 : ");
String inputPw = sc.nextLine();

if(userId.equals(inputId)) {
    if(userPw.equals(inputPw)) {
        System.out.println("로그인 성공");
    }else {
        System.out.println("비밀번호가 틀렸습니다.");
    }

}else {
    System.out.println("아이디가 틀렸습니다.");
}
sc.close();

문제 06.

사용자에게 관리자, 회원, 비회원 중 하나를 입력 받아 각 등급이 행할 수 있는 권한을 출력하세요.
단, 관리자는 회원관리, 게시글 관리, 게시글 작성, 게시글 조회, 댓글 작성이 가능하고 회원은 게시글 작성, 게시글 조회, 댓글 작성이 가능하고 비회원은 게시글 조회만 가능합니다.

Scanner sc = new Scanner(System.in);
System.out.print("권한을 확인하고자 하는 회원 등급 : ");
String grade = sc.nextLine();

switch(grade) {
case "관리자":
    System.out.print("회원관리, 게시글 관리 ");
case "회원":
    System.out.print("게시글 작성, 댓글 작성 ");
case "비회원":
    System.out.print("게시글 조회");
}
sc.close();

문제 07.

키, 몸무게를 double로 입력 받고 BMI지수를 계산하여 계산 결과에 따라 저체중/정상체중/과체중/비만을 출력하세요.
BMI = 몸무게 / (키(m) * 키(m))
BMI가 18.5미만일 경우 저체중 / 18.5이상 23미만일 경우 정상체중
BMI가 23이상 25미만일 경우 과체중 / 25이상 30미만일 경우 비만
BMI가 30이상일 경우 고도 비만

Scanner sc = new Scanner(System.in);

System.out.print("키(m)을 입력해 주세요 : ");
double height = sc.nextDouble();

System.out.print("몸무게(kg)를 입력해 주세요 : ");
double weight = sc.nextDouble();

double bmi = weight/(height * height);

System.out.println("BMI 지수 : " + bmi);

if(bmi < 18.5) {
    System.out.println("저체중");
}else if (bmi < 23) {
    System.out.println("정상체중");
}else if (bmi < 25) {
    System.out.println("과체중");
}else if (bmi < 30) {
    System.out.println("비만");
}else {
    System.out.println("고도비만");
}
sc.close();

문제 08.

키보드로 두 개의 정수와 연산 기호를 입력 받아 연산 기호에 맞춰 연산 결과를 출력하세요.
(단, 두 개의 정수 모두 양수일 때만 작동하며 없는 연산 기호를 입력 했을 시 “잘못 입력하셨습니다. 프로그램을 종료합니다.” 출력)

Scanner sc = new Scanner(System.in);

System.out.print("피연산자1 입력 : ");
double num1 = sc.nextDouble();

System.out.print("피연산자2 입력 : ");
double num2 = sc.nextDouble();
sc.nextLine();

System.out.print("연산자를 입력(+,-,*,/,%) : ");
String op = sc.nextLine();		

double result = 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("잘못 입력하셨습니다. 프로그램을 종료합니다.");
    sc.close();
    return;
}
System.out.println(num1 + " " + op + " " + num2 + " = " + result);
sc.close();

문제 09.

중간고사, 기말고사, 과제점수, 출석회수를 입력하고 Pass 또는 Fail을 출력하세요.
평가 비율은 중간고사 20%, 기말고사 30%, 과제 30%, 출석 20%로 이루어져 있고 이 때, 출석 비율은 출석 회수의 총 강의 회수 20회 중에서 출석한 날만 따진 값으로 계산하세요.
70점 이상일 경우 Pass, 70점 미만이거나 전체 강의에 30% 이상 결석 시 Fail을 출력하세요.

Scanner sc = new Scanner(System.in);

System.out.print("중간 고사 점수 : ");
double middleScore = sc.nextDouble();
double mScoreEx = middleScore * 0.2;

System.out.print("기말 고사 점수 : ");
double finalScore = sc.nextDouble();
double fScoreEx = finalScore * 0.3;

System.out.print("과제 점수 : ");
double projectScore = sc.nextDouble();
double pScoreEx = (projectScore * 0.3);

System.out.print("출석 점수 : ");
int attendanceScore = sc.nextInt();
double aScoreEx = attendanceScore;
double result = mScoreEx + fScoreEx + pScoreEx + aScoreEx;

if(attendanceScore <= 20-(20 * 0.3)) {
    System.out.println("===========결과===========");
    System.out.printf("fail [출석 회수 부족 (%d/20)]\n",attendanceScore);
}else {
    System.out.println("===========결과===========");
    System.out.printf("중간 고사 점수(20) : %.1f\n",mScoreEx);
    System.out.printf("기말 고사 점수(30) : %.1f\n",fScoreEx);
    System.out.printf("과제 점수    (20) : %.1f\n",pScoreEx);
    System.out.printf("츨석 점수    (20) : %.1f\n",aScoreEx);
    System.out.printf("총점 : %.1f\n",result);
    if(result >= 70) {
        System.out.println("PASS");
    }else {
        System.out.println("Fail [점수 미달]");
    }
}
sc.close();

문제 10.

앞에 구현한 실습문제를 선택하여 실행할 수 있는 메뉴화면을 구현하세요.

Scanner sc = new Scanner(System.in);

System.out.print("실행할 기능을 선택하세요.\n1.메뉴 출력 \n2.짝수/홀수 \n3. 합격/불합격 "
        + "\n4. 계절 \n5. 로그인 \n6. 권한 확인 \n7. BMI \n8. 게산기 \n9. P/F \n선택 : ");

int func = sc.nextInt();

switch(func) {
case 4:
    practice4();
    break;
}

sc.close();

 

    'JAVA' 카테고리의 다른 글
    • [자바/JAVA] 프로그래밍 - 제어문 종합 실습 예제
    • [자바/JAVA] 프로그래밍 - 반복문(for,while) 실습 예제
    • [자바/JAVA] 프로그래밍 - 제어문 (반복문 do-while)
    • [자바/JAVA] 프로그래밍 - 제어문 (반복문 while)
    21종
    21종
    코딩 공부한 것 정리하려고 만든 블로그

    티스토리툴바