조건문

Dec 14, 2023
조건문

If - else문

package ex03; import java.util.Scanner; public class EvenOdd { public static void main(String[] args) { int number; Scanner sc = new Scanner(System.in); System.out.println("정수를 입력하시오: "); number = sc.nextInt(); if(number % 2 == 0){ System.out.println("짝수"); } else{ System.out.println("홀수"); } } }
notion image
notion image
 

다중 If - else문

package ex03; import java.util.Scanner; public class Nested { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("정수를 입력하시오: "); int number = sc.nextInt(); if(number > 0){ System.out.println("양수입니다."); } else if(number == 0){ System.out.println("0입니다."); } else{ System.out.println("음수입니다."); } } }
notion image
notion image
notion image

Switch문

가독성이 좋아질 수 있음
switch(){ case 1 결과 break; case 2 결과 break; default 그외의 결과 break; }
 

연습문제


1) 성적 처리 예제
종종 우리는 조건에 따라서 다중으로 분기되는 결정을 내려야 하는 경우가 있다. 학생들의 성적을 받아서 학점을 출력하는 프로그램을 작성하여 실행하여 보자. 성적이 90점 이상이면 A학점, 80점 이상이고 90점 미만이면 B학점, 70점 이상이고 80점 미만이면 C학점과 같이 결정하는 것이다.
package ex03; import java.util.Scanner; public class Garding { public static void main(String[] args) { //1. 성적 입력받기 Scanner sc = new Scanner(System.in); System.out.print("성적을 입력하시오: "); int grade = sc.nextInt(); //2. 성적에 따른 학점 주기 if(grade >= 90){ System.out.println("학점 A"); } else if (grade >= 80) { System.out.println("학점 B"); } else if (grade >= 70) { System.out.println("학점 C"); } else if (grade >= 60) { System.out.println("학점 D"); } else{ System.out.println("학점 F"); } } }
notion image
 
2) 가위, 바위, 보 게임
가위, 바위, 보 게임을 작성해보자.
사용자가 가위, 바위, 보 중에서 하나를 선택하면
이것을 컴퓨터가 생성한 난수값과 비교한다.
누가 이겼는지를 화면에 출력한다.
package ex03; import java.util.Scanner; public class RockPaperScissor { public static void main(String[] args) { //1. 가위 바위 보 설정 final int SCISSOR = 0; final int ROCK = 1; final int PAPER = 2; //2. 가위 바위 보 입력받기 Scanner sc = new Scanner(System.in); System.out.print("가위(0), 바위(1), 보(2): "); int user = sc.nextInt(); //3. 컴퓨터가 랜덤함수로 가위 바위 보 선택하기 int computer = (int) (Math.random() * 3); System.out.print("인간: " + user + " 컴퓨터: " + computer); //4. 결과 안내하기 if(user == computer){ System.out.println(" 비겼습니다"); } else if (user == (computer + 1) % 3) { System.out.println(" 인간 승리"); } else { System.out.println(" 컴퓨터 승리"); } } }
notion image
💡
Math.random() : 난수 생성 (0부터 시작)

Share article
RSSPowered by inblog