[Java] 제어문과 연산자 + Java vs Python 차이

전주은·2023년 3월 5일
0
post-thumbnail

✔ 제어문 종류

조건문

1. if문

// 1. 기본 
if (조건식) {
    // 조건식이 참일 때 실행할 코드
}

if (조건식1) {
    // 조건식1이 참일 때 실행할 코드
} else if (조건식2) {
    // 조건식2가 참일 때 실행할 코드
} else {
    // 모든 조건식이 거짓일 때 실행할 코드
}

✨ 위에 있는 조건이 true라면 뒤에 있는 조건은 더이상 판별하지 않고 나간다.

2. switch문

switch (변수 또는 값) {
    case1:
        // 값1일 때 실행할 코드
        break;
    case2:
        // 값2일 때 실행할 코드
        break;
    // ...
    default:
        // 모든 case에 해당하지 않을 때 실행할 코드
        break;
}

✨ if문은 범위일때, switch문 특정값일때 사용하는 것이 편리하다.

👀 break문

  • switch문 또는 반복문(for,while)을 벗어날 때 사용한다.
  • if문을 빠져나가는게 아니고 반복문을 빠져나간다.
for(변수; 조건식; 증감식){
    ...
    if(조건식) break;
    ...
}

반복문

1. for문

for (초기화; 조건식; 증감식) {
    // 실행될 코드
}

2. while문

while (조건식) {
    // 실행될 코드
}

3. do-while문

do-while문은 while문과 비슷한 반복문이지만, 먼저 한 번은 실행된 후 조건식을 평가한다.

do {
    // 실행될 코드
} while (조건식);

향상된 for문

for (타입 변수명 : 배열 또는 컬렉션) {
    // 실행할 코드
}

int[] arr = {1, 2, 3, 4, 5};

// 일반적인 for문
for (int i = 0; i < arr.length; i++) {
    int num = arr[i];
    System.out.println(num);
}

// 향상된 for문
for (int num : arr) {
    System.out.println(num);
}

중첩 반복문

// while문
while(조건식1){
    조건식1true인 동안 반복할 문장;
    ...
    while(조건식2){
        조건식2true인 동안 반복할 문장;
        ...
    }
}
// for문
for(변수; 조건식1; 증감식){
    조건식1true인 동안 반복할 문장;
    ...
    for(변수; 조건식2; 증감식){
        조건식2true인 동안 반복할 문장;
        ...
    }
}

✔ 연산자에 대한 소개

1. 산술 연산자

int a = 10;
int b = 3;

int result1 = a + b;    // 13
int result2 = a - b;    // 7
int result3 = a * b;    // 30
int result4 = a / b;    // 3
int result5 = a % b;    // 1

2. 증감 연산자

int i = 0;

// 전위 증감 연산자
++i; // i의 값은 1 증가한 후 1이 됨
--i; // i의 값은 1 감소한 후 0이 됨

// 후위 증감 연산자
i++; // i의 값은 1이 되고, 다음 표현식에서는 1을 반환함
i--; // i의 값은 0이 되고, 다음 표현식에서는 0을 반환함

3. 비교 연산자

int a = 10;
int b = 3;

boolean result1 = a > b;     // true
boolean result2 = a < b;     // false
boolean result3 = a >= b;    // true
boolean result4 = a <= b;    // false
boolean result5 = a == b;    // false
boolean result6 = a != b;    // true

4. 논리 연산자

boolean a = true;
boolean b = false;

boolean result1 = a && b;    // false
boolean result2 = a || b;    // true
boolean result3 = !a;        // false
boolean result4 = !b;        // true

5. 비트 연산자

연산자설명예시
& (비트 AND)각 비트를 AND 연산1100 & 1010 = 1000
| (비트 OR)각 비트를 OR 연산1100 | 1010 = 1110
^ (비트 XOR)각 비트를 XOR 연산1100 ^ 1010 = 0110
~ (비트 NOT)각 비트를 반전~1100 = 0011
<< (비트 왼쪽 시프트)각 비트를 왼쪽으로 이동0011 << 2 = 1100
>> (비트 오른쪽 시프트)각 비트를 오른쪽으로 이동1100 >> 2 = 0011
>>> (부호 없는 비트 오른쪽 시프트)각 비트를 오른쪽으로 이동, 왼쪽 끝 비트에 0을 채움1100 >>> 2 = 0011

6. 삼항 연산자

int x = 5;
String message = (x > 10) ? "x는 10보다 큽니다" : "x는 10보다 작거나 같습니다";
System.out.println(message);

7. instanceof 연산자

  • 객체가 어떤 클래스의 인스턴스인지 판별하는 데 사용
object instanceof class

8. 연산자 우선순위

우선순위연산자설명
1()괄호
2++, --후위 증가/감소
+, -단항 양수/음수
!논리 부정
~비트 반전
(type)형 변환
new객체 생성
3* / %곱셈, 나눗셈, 나머지
4+, -덧셈, 뺄셈
5<<, >>시프트
6<, <=, >, >=, instanceof관계
7==, !=같음, 다름
8&비트 AND
9^비트 XOR
10|비트 OR
11&&논리 AND
12||논리 OR
13? :삼항 연산자
14=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=할당

✔ 제어문과 연산자를 이용한 가위바위보 게임

import java.util.Random;
import java.util.Scanner;

public class RockPaperScissors {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        Random random = new Random();

        String[] choices = {"가위", "바위", "보"};
        System.out.println("가위바위보 게임을 시작합니다.");

        while (true) {
            System.out.print("가위, 바위, 보 중 하나를 선택하세요: ");
            String userChoice = scanner.nextLine();
            int computerIndex = random.nextInt(3);
            String computerChoice = choices[computerIndex];

            System.out.printf("사용자: %s, 컴퓨터: %s\n", userChoice, computerChoice);

            // 사용자가 유효한 선택을 했는지 검사합니다.
            if (!userChoice.equals("가위") && !userChoice.equals("바위") && !userChoice.equals("보")) {
                System.out.println("유효하지 않은 선택입니다.");
                continue;
            }

            // 결과를 비교하여 승자를 출력합니다.
            if (userChoice.equals(computerChoice)) {
                System.out.println("비겼습니다.");
            } else if ((userChoice.equals("가위") && computerChoice.equals("보")) ||
                       (userChoice.equals("바위") && computerChoice.equals("가위")) ||
                       (userChoice.equals("보") && computerChoice.equals("바위"))) {
                System.out.println("사용자 승리!");
            } else {
                System.out.println("컴퓨터 승리!");
            }

            // 게임을 계속할지 종료할지 묻습니다.
            System.out.print("게임을 계속하시겠습니까? (Y/N) ");
            String answer = scanner.nextLine();
            if (!answer.equals("Y")) {
                break;
            }
        }

        System.out.println("게임을 종료합니다.");
        scanner.close();
    }
}

✔ 제어문과 연산자를 이용한 파일 입출력 프로그램 예제

import java.util.Scanner;
import java.io.*;

public class FileIOExample {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String filename;
        System.out.print("Enter the file name: ");
        filename = scanner.nextLine();

        try {
            File file = new File(filename);
            if (!file.exists()) {
                System.out.println("The file does not exist.");
                System.exit(0);
            }
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            String line;
            System.out.println("Contents of " + filename + ":");
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
            fr.close();
            System.out.println("File read successfully.");

            System.out.print("Enter text to write to the file: ");
            String text = scanner.nextLine();
            FileWriter fw = new FileWriter(file, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(text);
            bw.newLine();
            bw.close();
            fw.close();
            System.out.println("Text written to the file successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

✔ Java vs Python

구분JavaPython
조건문if, else if, elseif, elif, else
삼항 연산자조건식 ? 참일 때 값 : 거짓일 때 값참일 때 값 if 조건식 else 거짓일 때 값
논리 연산자&& (and), || (or), ! (not)and, or, not
비트 연산자>>>부호 없는 비트 오른쪽 시프트) 연산자없음

0개의 댓글