[JAVA] 5. 조건문 Ⅰ. if-else 문

최재원's avatar
Feb 05, 2025
[JAVA] 5. 조건문 Ⅰ. if-else 문
if (조건문) { 참 } else { 거짓 }
notion image

1. 홀수, 짝수 판별하기

package ex03; // if-else 문 import java.util.Scanner; // 클래스명 = 파일명과 동일 // 클래스명 규칙 = 파스칼 표기법 // 첫글자 대문자, 단어구분 대문자 public class EvenOdd { public static void main(String[] args) { String result; int num; // 1. 키보드에서 숫자 입력 받기 System.out.print("정수를 입력하시오: "); Scanner sc = new Scanner(System.in); num = sc.nextInt(); // 2. 홀수, 짝수 판별하기 if (num % 2 == 0) { // 짝수 result = "입력된 정수는 짝수입니다."; } else { result = "입력된 정수는 홀수입니다."; } // 3. 출력하기 System.out.println(result); } }
notion image

2. 음수, 양수 판별하기

package ex03; // 다중 if-else 문 import java.util.Scanner; public class Nested { public static void main(String[] args) { String result; int num; // 1. 숫자 입력 받기. System.out.print("정수를 입력하시오: "); Scanner sc = new Scanner(System.in); num = sc.nextInt(); // 2. 양수, 음수, 0 판별하기. if (num > 0) { result = "양수입니다."; } else if (num < 0) { result = "음수입니다."; } else { result = "숫자 0입니다."; } // 3. 출력하기 System.out.println(result); } }
notion image

3. 성적에 따른 학점 판별하기

package ex03; import java.util.Scanner; public class Grading { public static void main(String[] args) { int grade; String result; // 1. 성적 입력 받기 System.out.print("성적을 입력하시오: "); Scanner sc = new Scanner(System.in); grade = sc.nextInt(); // 2. 성적에 따른 학점 판별하기. if (grade >= 90) { result = "학점 A"; } else if (grade >= 80) { result = "학점 B"; } else if (grade >= 70) { result = "학점 C"; } else if (grade >= 60) { result = "학점 D"; } else { result = "학점 F"; } // 3. 학점 출력하기. System.out.println(result); } }
notion image

4. 컴퓨터 vs 인간 가위바위보

package ex03; import java.util.Scanner; public class RockPaperScissor { public static void main(String[] args) { int user; String result; final int SCISSOR = 0; final int ROCK = 1; final int PAPER = 2; // 1. 유저에게 입력받기. System.out.print("가위(0) | 바위(1) | 보(2): "); Scanner sc = new Scanner(System.in); user = sc.nextInt(); // 2. 인간과 컴퓨터의 값을 비교 int computer = (int) (Math.random() * 3); if (user == computer) { result = "인간과 컴퓨터가 비겼음."; } else if (user == (computer + 1) % 3) { result = "인간: " + user + " 컴퓨터: " + computer + " 인간승리"; } else { result = "인간: " + user + " 컴퓨터: " + computer + " 컴퓨터승리"; } if (0 > user || user > 2) { result = "잘못된 숫자를 입력하였습니다."; } // 3. 결과 출력 System.out.println(result); } }
notion image
Share article

jjack1