Difference between revisions of "컴퓨터프로그래밍및실습 (2022년)/0908"

From DISLab
Jump to navigation Jump to search
Line 356: Line 356:
else
else
     grade = 'B';
     grade = 'B';
</syntaxhighlight>
== 조건문 ==
=== if 문 ===
<syntaxhighlight lang="java">
public class IfExample {
    public static void main(String[] args) {
        int score = 93;
        //-----------------------------------------
        // if 문
        //-----------------------------------------
        if (score >= 90) {
            System.out.println("A");
        }
        if (score < 90) {
            System.out.println("B");
        }
        //-----------------------------------------
        // if-else 문
        //-----------------------------------------
        if (score >= 90) {
            System.out.println("A");
        } else {
            System.out.println("B");
        }
        //-----------------------------------------
        // if-else if-else 문
        //-----------------------------------------
        if (score >= 90) {
            System.out.println("A");
        } else if (score >= 80) {
            System.out.println("B");
        } else if (score >= 70) {
            System.out.println("C");
        } else if (score >= 60) {
            System.out.println("D");
        } else {
            System.out.println("F");
        }
        //-----------------------------------------
        // 중첩 if 문
        //-----------------------------------------
        if (score >= 90) {
            if (score >= 95) {
                System.out.println("A+");
            } else {
                System.out.println("A0");
            }
        } else {
            if (score >= 85) {
                System.out.println("B+");
            } else {
                System.out.println("B0");
            }
        }
    }
}
</syntaxhighlight>
=== switch 문 ===
<syntaxhighlight lang="java">
public class SwitchExample {
    public static void main(String[] args) {
        int num = (int) (Math.random() * 10); // 0 ~ 9
        switch(num) {
            case 1 :
                System.out.println("1");
                break;
            case 2 :
                System.out.println("2");
                break;
            case 3 :
                System.out.println("3");
            case 4 :
                System.out.println("4");
                break;
            case 5 :
            case 6 :
            case 7 :
                System.out.println("789");
                break;
            default :
                System.out.println("OOPS");
                break; // break가 필요한가?
        }
        //----------------------------
        //  문자
        //----------------------------
        char grade = (char)('A' + num);
        switch(grade) {
            case 'A' :
                System.out.println("A");
                break;
            case 'B' :
                System.out.println("B");
                break;
            case 'C' :
                System.out.println("C");
                break;
            case 'D' :
                System.out.println("D");
                break;
            default:
                System.out.println("F");
                break;
        }
        //----------------------------
        //  String (JDK 7부터)
        //----------------------------
        String str = "과장";
        switch(str) {
            case "부장" :
                System.out.println("700만원");
                break;
            case "과장" :
                System.out.println("500만원");
                break;
            default:
                System.out.println("300만원");
        }
    }
}
</syntaxhighlight>
== 반복문 ==
=== for 문 ===
* 1 ~ 100까지 더하는 연산
<syntaxhighlight lang="java">
int sum = 0;
for(int i = 1; i <= 100; i++) {
    sum += i;
}
System.out.println("1~" + (i - 1) + 까지의 합 : " + sum);
</syntaxhighlight>
<table2 sep=bar align=cccc>
for (|<u>int i = 0, j = 100</u>; |  <u>i <= 50 && j >= 50</u>; | <u>i++, j--</u>|) {
    | 초기화식                  | 조건식                      | 증감식
</table2>
=== while 문 ===
* 1 ~ 100까지 더하는 연산
<syntaxhighlight lang="java">
int sum = 0;
int i = 1;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("1~" + (i - 1) + 까지의 합 : " + sum);
</syntaxhighlight>
=== do-while 문 ===
* 1 ~ 100까지 더하는 연산
<syntaxhighlight lang="java">
int sum = 0;
int i = 1;
do {
    sum += i;
    i++;
} while (i <= 100);
System.out.println("1~" + (i - 1) + 까지의 합 : " + sum);
</syntaxhighlight>
* System.in 객체를 이용하여 키보드로부터 값을 읽어들이는 방법
<syntaxhighlight lang="java">
int keyCode = System.in.read();
if (keyCode == 49) { // 1을 읽었을 경우
</syntaxhighlight>
* Key Code
<table2 class=wikitable head=top sep=bar align=cccccccccccc>
키 | 키코드 | 키 | 키코드 | 키 | 키코드 | 키 | 키코드 | 키 | 키코드 | 키        | 키코드      | 키 | 키코드
0  | 48    | A  | 65    | N  | 78    | a  | 97    | n  | 110    | Backspace | 8            | ← | 37
1  | 49    | B  | 66    | O  | 79    | b  | 98    | o  | 111    | Tab      | 9            | ↑ | 38
2  | 50    | C  | 67    | P  | 80    | c  | 99    | p  | 112    | Enter    | CR=13, LF=10 | → | 39
3  | 51    | D  | 68    | Q  | 81    | d  | 100    | q  | 113    | Shift    | 16          | ↓ | 40
4  | 52    | E  | 69    | R  | 82    | e  | 101    | r  | 114    | Ctrl      | 17          |    |
5  | 53    | F  | 70    | S  | 83    | f  | 102    | s  | 115    | Alt      | 18          |    |
6  | 54    | G  | 71    | T  | 84    | g  | 103    | t  | 116    | ESC      | 27          |    |
7  | 55    | H  | 72    | U  | 85    | h  | 104    | u  | 117    | Space    | 32          |    |
8  | 56    | I  | 73    | V  | 86    | i  | 105    | v  | 118    | PAGEUP    | 33          |    |
9  | 57    | J  | 74    | W  | 87    | j  | 106    | w  | 119    | PAGEDOWN  | 34          |    |
  |        | K  | 75    | X  | 88    | k  | 107    | x  | 120    |          |              |    |
  |        | L  | 76    | Y  | 89    | l  | 108    | y  | 121    |          |              |    |
  |        | M  | 77    | Z  | 90    | m  | 109    | z  | 122    |          |              |    |
</table2>
* Scanner 객체를 이용하여 값을 읽어들이는 방법
<syntaxhighlight lang="java">
import java.util.Scanner;
public class ScannerExample {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int v1 = scan.nextInt();
        double v2 = scan.nextDouble();
        boolean v3 = scan.nextBoolean();
       
        String str = scan.next();
        String line = scan.nextLine();
    }
}
</syntaxhighlight>
=== break 문 ===
* 자신이 속한 반복문 탈출
<syntaxhighlight lang="java">
int sum = 0;
int i = 1;
while (true) {
    sum += i;
    if (i == 0)
        break; // 반복문 탈출
}
System.out.println(sum);
</syntaxhighlight>
* 지정한 반복문 탈출
<syntaxhighlight lang="java">
Outer:
for (char upper = 'A'; upper <= 'Z'; upper++) {
    for(char lower = 'a'; lower <= 'z'; lower++) {
        System.out.println(upper + "-" + lower);
        if (lower == 'g')
            break Outer;
    }
}
</syntaxhighlight>
<syntaxhighlight lang="text">
A-a
A-b
A-c
A-d
A-e
A-f
A-g
</syntaxhighlight>
=== continue 문 ===
* continue 문을 이용하여 짝수만 출력
<syntaxhighlight lang="java">
for(int i = 1; i <= 10; i++) {
    if (i % 2 != 0)  // 짝수가 아니라면, 즉 홀수
        continue;
    System.out.println(i);
}
</syntaxhighlight>
* 지정한 반복문으로 점프
<syntaxhighlight lang="java">
Outer:
for (char upper = 'A'; upper <= 'C'; upper++) {
    for(char lower = 'a'; lower <= 'z'; lower++) {
        System.out.println(upper + "-" + lower);
        if (lower == 'g')
            continue Outer;
    }
}
</syntaxhighlight>
<syntaxhighlight lang="text">
A-a
A-b
A-c
A-d
A-e
A-f
A-g
B-a
B-b
B-c
B-d
B-e
B-f
B-g
C-a
C-b
C-c
C-d
C-e
C-f
C-g
</syntaxhighlight>
</syntaxhighlight>




[[category:컴퓨터프로그래밍및실습]]
[[category:컴퓨터프로그래밍및실습]]

Revision as of 14:14, 20 July 2022

연산자

연산자와 연산식

연산자 종류 연산자 피연산자 수 산출값 기능 설명
산술 +, -, *, /, % 이항 숫자 사칙연산 및 나머지 연산 2 + 3
부호 +, - 단항 숫자 음수와 양수의 부호 -2
문자열 + 이항 문자열 두 문자열을 연결 "abc" + "def"
대입 =, +=, -=, *=, /=, %=, &=
^=, !=, <<=, >>=, >>>=
이항 다양 우변의 값을 좌변의 변수에 대입 i += 3
증감 ++, -- 단항 숫자 1만큼 증가/감소 i++
비교 ==, !=, >, <, >=, <=
instanceof
이항 boolean 값의 비교 i > j
논리 !, &, |, &&, || 단항
이항
boolean 논리적 NOT, AND, OR 연산 !(a < 3), (a < 3) && (a > 1)
조건 (조건식) ? A : B 삼항 다양 조건식에 따라 A 또는 B 중 하나를 선택 a = (x > y) ? x : y
비트 ~, &, |, ^ 단항
이항
숫자
boolean
비트 NOT, AND, OR, XOR 연산 ~a, a & b
쉬프트 >>, <<, >>> 이항 숫자 비트를 좌측/우측으로 밀어서 이동 a >> 3

연산의 방향과 우선순위

x > 0 && y < 0 // 어떤 순으로 연산될 것인가?

v1 = 100 * 2 / 3 % 5; // v1 = (((100 * 2) / 3) % 5)

a = b = c = 5; // (a = (b = (c = 5)));
  • 연산자 우선순위
연산자 연산 방향 우선 순위
++, --, +, -, ~, ! 높음
*, /, %
+, -
<<, >>, >>>
<, >, <=, >=, instanceof
==, !=
&
^
|
&&
||
? :
=, +=, -=, *=, /=, %=, &=, ^=, |=, <<=, >>=, >>>= 낮음

int var1 = 1;
int var2 = 3;
int var3 = 2;
int result = var1 + var2 * var3;

int result = (var1 + var2) * var3;

단항 연산자

부호 연산자

int i1 = +100;  // 부호 + (양수)
int i2 = -100;  // 부호 - (음수)
double d1 = +3.14;

int x = -100;
int result1 = -x; // OK

short s1 = 100;
short s2 = -s1; // 오류. 정수 연산은 int로 바뀌기 때문
int i3 = -s1; // OK

증감 연산자(++, --)

++i;
i++;

--i;
i--;

//------------------
int x = 10;
int z;

z = ++x;

// 위 코드는 아래와 동일
x = x + 1;
z = x;

//-------------------
int x = 10;
int z;

z = x++;

// 위 코드는 아래와 동일
z = x;
x = x + 1;

//------------------
int x = 10;
int z;

z = --x;

// 위 코드는 아래와 동일
x = x - 1;
z = x;

//-------------------
int x = 10;
int z;

z = x--;

// 위 코드는 아래와 동일
z = x;
x = x - 1;

논리 부정 연산자 !

boolean play = true;

play = !play;

비트 반전 연산자 ~

byte v1 = 10; // 00001010
byte v2 = ~v1; // 오류. 정수 종류의 연산은 자동으로 int로 변환됨

int i2 = ~v1; // OK. 11111111 11111111 11111111 11110101

int i3 = ~v1 + 1; // -10 (2의 보수)

System.out.println( Integer.toBinaryString(i3) );

이항 연산잔

산술 연산자

byte byte1 = 1;
byte byte2 = 1;
byte byte3 = byte1 + byte2; // 오류. 정수 타입의 산술 연산은 32비트인 int로 형변환됨

int result1 = byte1 + byte2; // OK

int int1 = 10;
int int2 = 4;
int result2 = int1 / int2;  // 2
double result3 = int1 / int2; // 2.0

double result4 = (double) int1 / int2; // 2.5

char c1 = 'A' + 1; // OK 'B'
char c2 = 'A';
char c3 = c2 + 1; // 컴파일 에러. c2가 int로 형변환됨
오버플로우
int x = 1000000;
int y = 1000000;

int z = x * y; // z에는 오버플로우되어 -727379968와 같이 알 수 없는 값이 저장됨

//-------------

long x = 1000000;
long y = 1000000;

long z = x * y; // OK
정확한 계산은 정수 사용
int apple = 1;
double priceUnit = 0.1;
int number = 7;

double result = apple - number * priceUnit; // 0.3이 되어야 할 것 같지만 아님. 왜?

System.out.println(result); // 0.29999999999999993
NaN과 Infinity 연산
5 / 0  ArithmeticException 예외 발생
5 % 0  ArithmeticException 예외 발생

5 / 0.0  Infinity
5 % 0.0  NaN

double val = Double.valueOf("NaN"); // NaN 입력

if (Double.isNaN(val)) { // NaN인지 검사
    System.out.println("OOPS");
}

문자열 연결 연산자 (+)

String str1 = "JDK" + 6.0; // "JDK6.0"
String str2 = str1 + " 특징"; // "JDK6.0 특징"

String str3 = "JDK" + 3 + 3.0; // ("JDK" + 3) + 3.0 → ("JDK" + "3") + 3.0 → "JDK3" + "3.0" → "JDK33.0"
String str4 = 3 + 3.0 + "JDK"; // (3 + 3.0) + "JDK" → (3.0 + 3.0) + "JDK" → "6.0" + "JDK" → "6.0JDK"

비교 연산자

int num1 = 10;
int num2 = 10;

boolean result1 = num1 == num2;
boolean result2 = (num1 != num2);
boolean result3 = (num1 <= num2);

char char1 = 'A';
char char2 = 'B';

boolean result4 = (char1 < char2);

//------------------

'A' == 65  true
3 == 3.0  true
0.1 == 0.1f  false // 2진수로 변환하기 때문에 정확한 0.1 표현이 안됨. 
                     // 0.1을 2진수로 바꾸었다가 10진수로 변환하면 0.10000000149011612와 같이 표현됨

//------------------

String strVar1 = "신용권";
String strVal2 = "신용권";
String strVal3 = new String("신용권");

strVal1 == strVal2  true
strVar2 == strVal3  false

strVal1.equals(strVal2)  true
strVal2.equals(strVal3)  true // 내용으로 비교하기 때문

논리 연산자

구분 연산식 설명
AND && 모두 참일 때만 참
OR || 모두 거짓일 때만 거짓
XOR ^ 배타적 논리합. 하나는 true, 다른 하나는 false 일 때만 true
NOT ! 피연산자의 논리값을 바꿈

int charCode = 'A';

if (charCode >= 'A' && charCode <= 'Z') {
    System.out.println("대문자입니다");
}

비트 연산자

비트 논리 연산자
byte num1 = 45;
byte num2 = 25;

byte result1 = num1 & num2;
byte result2 = num1 | num2;
byte result3 = num1 ^ num2;
byte result4 = ~num1;
변수 십진수 연산
num1 00101101 45
num2 00011001 25
result1 00001001 9 num1 & num2
result2 00111101 61 num1 | num2
result3 00110100 52 num1 ^ num2
result4 11010010 -46 ~num1

비트 이동 연산자
int result1 = 1 << 3;
int result2 = -8 >> 3;
int result3 = -8 >>> 3;
변수 연산 이진값 비고
1 00000000 00000000 0000000 00000001
result1 8 1 << 3 00000000 00000000 0000000 00001000 23
-8 11111111 11111111 1111111 11111000
resutl2 -1 -8 >> 3 11111111 11111111 1111111 11111111
result3 536870911 -8 >>> 3 00011111 11111111 1111111 11111111

대입 연산자

  • 예제 코드
public class AssignmentOperatorExample {
    public static void main(String[] args) {
        int result = 0;

        result += 10; // result = result + 10;
        System.out.println(result);

        result -= 5; // result = result - 10;
        System.out.println(result);

        result *= 3; // result = result * 3;
        System.out.println(result);

        result /= 5; // result = result / 5;
        System.out.println(result);

        result %= 3;
        System.out.println(result);
    }
  • 실행 결과
10
5
15
3
0
  • 유용한 경우
int result *= x + y * z; // result = result * (x + y * z);

삼항 연산자

int score = 95;

char grade = (score > 90) ? 'A' : 'B';

// 아래와 동일한 의미의 코드이다.

int score = 95

char grade;
if (score > 90)
    grade = 'A';
else
    grade = 'B';