자바 수업 2일차



* 하드웨어에도 관심을 가지면 좋다.

  - 라즈베리파이, 아두이노


* 비트 연산자

  - 2진수로 표현된 정수를 비트 단위로 취급하는 연산자

  - 비트 논리 연산자

    · & : AND  (예) 5&7

    · | : OR  (예) 5|7

    · ^ : XOR(eXclusive OR)  (예) 5^7

    · ~ : NOT(부정, 1의 보수)  (예) ~5


* 시프트 연산자

  - 비트 단위로 이동하는 연산자

  - 하드웨어에서 많이 사용

  - 정수를 좌우로 시프트하면 곱셈과 나눗셈의 결과가 나온다.

    · << : 곱하기  (예) a << n, 정수 a를 비트 단위로 왼쪽으로 n비트 시프트한다. 비게 된 비트에는 0으로 채운다.

    · >> : 나누기  (예) a >> n, 정수 a를 비트 단위로 오른쪽으로 n비트 시프트한다. 비게 된 비트에는 시프트 전의 부호 비트로 채운다.

    · >>> : (예) a >>> n, 정수 a를 비트 단위로 오른쪽으로 n비트 시프트한다. 비게 된 비트에는 0으로 채운다. 부호 비트를 고려하지 않기 때문에 a가 음수일 경우 시프트 결과는 양수로 나타낸다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.Scanner;
 
public class ShiftOPTest1 {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
 
        System.out.println("두 개의 숫자를 입력 : ");
 
        int a = stdin.nextInt();
        int b = stdin.nextInt();
 
        System.out.println("    a = " + a + "(" + Integer.toBinaryString(a) +")");
        System.out.println("    b = " + b + "(" + Integer.toBinaryString(b) +")");
        System.out.println(" a<<2 = " + (a<<2+ "(" + Integer.toBinaryString(a<<2+ ")");
        System.out.println(" a>>2 = " + (a>>2+ "(" + Integer.toBinaryString(a>>2+ ")");
        System.out.println(" b<<2 = " + (b<<2+ "(" + Integer.toBinaryString(b<<2+ ")");
        System.out.println(" b>>2 = " + (b>>2+ "(" + Integer.toBinaryString(b>>2+ ")");
        System.out.println("b>>>2 = " + (b>>>2+ "(" + Integer.toBinaryString(b>>>2+ ")");
        System.out.println("b>>>3 = " + (b>>>3+ "(" + Integer.toBinaryString(b>>>3+ ")");
        System.out.println("b>>>4 = " + (b>>>4+ "(" + Integer.toBinaryString(b>>>4+ ")");
        System.out.println("b>>>30 = " + (b>>>30+ "(" + Integer.toBinaryString(b>>>30+ ")");
    }
}
cs


    ※ 이클립스 콘솔에서는, 앞에 채운 0이 생략되어 찍힌다.

      CMD에서도 마찬가지로 0이 생략됨을 확인하였음!


* 3항 연산자

  - 수식1 ? 수식2 : 수식3

  예) int a = 11;

      flag = a>=10 ? true : false

      System.out.println(flag);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Scanner;
 
public class TernaryOPTest {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
 
        System.out.println("한 개의 숫자를 입력 : ");
        int a = stdin.nextInt();  // 정수를 입력받는다.        
 
        boolean flag;
        flag = (a % 2 == 0) ? true : false;        
 
        System.out.println(a + "이(가) 짝수입니까? : ");
        System.out.println(flag);
    }
}
cs

* 자바의 문자열
  - 기본 자료형이 아닌 String 클래스로 구현되는 참조 자료형이다.
  - 문자열과 정수를 연산할 때는 정수의 연산이 먼저 계산된다.
    예) System.out.println(a + b + "리 금수강산"); -> (a+b)가 먼저 계산됨.

* 선택문
  - if문 / 조건식 / switch문

* 이중 if문
if (grade >= 90)
  System.out.println("A학점 취득 성공");
else
  System.out.println("A학점 취득 실패");

위의 문장을 3항 연산자를 이용하면
System.out.println(grade >= 90 ? "A학점 취득 성공" : "A학점 취득 실패");

한 문장으로 표현 가능하다.

* 선택문 안에 선택문이 내포될 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
if (조건식)
{
    if (조건식)
    {
        ...
    }
    else
    {
        if (조건식)
        {
            ...
        }
    }
}
cs

※ 하지만 이딴 식으로 작성하면 읽기가 곤란해진다.
  들여쓰기를 잘 해서(확실하게 눈에 띄게), 줄을 잘 맞추자.

* 개발하려는 프로그램의 핵심은 조건식
  - 일반적인 문제에서 조건식을 명확하게 추출하는 것이 프로그램의 핵심
  - 많이 해보는 수밖에 없다.

* 드모르간의 법칙
  - 특히 소프트웨어에서는 굳이 알 필요 없다.
  - a && b는 !(!a || !b)과 같습니다.
  - a || b는 !(!a && !b)와 같습니다.
    예)
    1. (score1 >= 80 || score2 >= 80)  ==  !(score1 < 80 && score2 < 80)
    2. (score > 60 && score <= 100)  ==  !(score <= 60 || score > 100)
    3. (input1 % 2 == 0 && input2 % 2 == 0)  ==  !(input1 % 2 != 0 || input2 % 2 != 0)

* 논리 연산자와 비트 논리 연산자는 다르게 동작한다.
int a=10, b=20;
System.out.println((a >= 20) & (b >= 20));  <- false 출력
System.out.println((a >= 20) && (b >= 20));  <- false 출력

  - 결과는 같지만 실제 실행은 다르다.
  - 논리 연산자는 단락 평가 연산자로서 한 쪽을 평가하여 다른 한 쪽을 평가할 필요가 없는 경우 바로 결과를 반환하지만, 비트 논리 연산자는 그 경우에도 남은 부분을 수행한다.

* switch-case문
  - if-else문과의 차이점
    ~ if문에서는 조건식에서 판단이 다 끝나버린다.
    예)
    if (a == 1)
    else if (a == 2)
    else if (a == 3)
    ~ switch문에서는
    예)
    switch(n)
      case 1:
      case 2:
      case 3:
  - switch문에서 주의할 점
    ~ true가 나오는 case부터 시작한다.
      위의 코드에서 n=2라면, case 2부터 시작해서 3, 4, ... 식으로 계속 진행한다.
      필요한 경우 case마다 break를 넣어줘야 한다.
  - switch문의 default문 == if문의 else문

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import java.util.Scanner;
public class SwitchTest1 {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        System.out.println("월을 입력하세요 : ");
        int month = stdin.nextInt();
        String MtoS;
        switch (month)
        {
            case 12:
            case 1:
            case 2:
                MtoS = "겨울입니다.";
                break;
            case 3:
            case 4:
            case 5:
                MtoS = "봄입니다.";
                break;
            case 6:
            case 7:
            case 8:
                MtoS = "여름입니다.";
                break;
            case 9:
                System.out.print("멋진 9월과 ");
            case 10:
                System.out.print("아름다운 10월과 ");
            case 11:
                System.out.print("낙엽의 11월은 ");
                MtoS = "가을입니다.";
                break;
            default:
                MtoS = "제대로 입력하세요. -_-";
                break;
        }
        System.out.println(MtoS);
    }
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;
public class SwitchTest1_2 {
    public static void main(String[] args) {
        Scanner stdin = new Scanner(System.in);
        System.out.println("월을 입력하세요 : ");
        int month = stdin.nextInt();
 
        if ( (month == 12|| (month == 1|| (month == 2) )
            System.out.println("겨울입니다.");
        else if ( (month == 3|| (month == 4|| (month == 5) )
            System.out.println("봄입니다.");
        else if ( (month == 6|| (month == 7|| (month == 8) )
            System.out.println("여름입니다.");
        else if ( (month == 9|| (month == 10|| (month == 11) )
            System.out.println("가을입니다.");
        else
            System.out.println("제대로 입력하세요. -_-");
    }
}
cs


* 반복문

  - for문

1
2
3
4
5
6
7
8
9
public class ForTest1 {
    public static void main(String[] args) {
        int i, sum=0;
        for (i = 1; i <= 10; i++) {
            sum = sum + i;
        }
        System.out.println("1부터 10까지의 합은 " + sum + "입니다.");
    }
}
cs

1
2
3
4
5
6
7
8
9
10
11
12
public class ForTest1_2 {
    public static void main(String[] args) {
        int sum = 0;
        int count;
        int num = 1;
        
        for (count = 1; count <= 10; count++, num++) {
            sum = sum + num;
        }
        System.out.println("1부터 10까지의 합은 " + sum + "입니다.");
    }
}
cs


  - 반복문 기초 필수 코스, 바로... 구구단

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Test_9x9 {
    public static void main(String[] args) {
        // 구구단 9단
        // for문 사용
        
        // 반복 횟수 : 8회(1단 제외) 안에서 다시 9회 반복
        // 반복 시, 변화되는 내용 : 곱하는 숫자가 1씩 증가, 곱해지는 숫자도 1씩 증가.
        // 출력 내용 : ? x ? = ?
        
        int x = 0;
        int y = 0;
        
        System.out.println("구구단 출력하기");
        
        for (x=2; x<=9; x++) {   // 1단은 제외하고 2단부터 시작
            System.out.println("\n구구단 " + x + "단");
            for (y=1; y<=9; y++) {
                System.out.println(x + " x " + y + " = " + (x*y));
            }
        }
    }
cs


* 코딩 과제
  - 음료 자동 판매기
    ~ 음료 종류 : 콜라(800원), 생수(400원), 주스(1,000원)
    ~ 시나리오
      1. 지폐 1,000원 투입
      2. 생수 2개를 선택
      3-1. 반환 버튼 -> 200원 반환
      3-2. 1,000원 지폐 더 투입
      4. 콜라 1개 선택
      5. 생수 1병 선택


※ 주의 : 아래의 코드는 완벽하게 동작하지 않는 미완성 코드입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Scanner;
public class VendingMachine {
    public static void main(String[] args) {
    //  - 음료 자동 판매기
    //      ~ 음료 종류 : 콜라(800원), 생수(400원), 주스(1,000원)
    //      ~ 시나리오
    //        1. 지폐 1,000원 투입
    //        2. 생수 2개를 선택
    //        3-1. 반환 버튼 -> 200원 반환
    //        3-2. 1,000원 지폐 더 투입
    //        4. 콜라 1개 선택
    //        5. 생수 1병 선택
        
        int totalMoney = 0;  // 잔액 기억 변수
        Scanner objDrink = new Scanner(System.in);
        int yourChoice = -1;
        
        System.out.println("어서오세요. 음료 한 잔 하고 가세요 ^^");
        System.out.println("잔액은 " + totalMoney + "원입니다.");
        
        while(true)    {
            System.out.print("음료를 뽑으시려면 돈을 투입해주세요.\n금액 : ");
            Scanner objMoney = new Scanner(System.in);
            int moneyInput = objMoney.nextInt();
            
            if (moneyInput > 0) {  // 투입된 금액이 있으면
                totalMoney = totalMoney + moneyInput;
                System.out.println("현재 잔액은 " + totalMoney + "원입니다.");
                
                // 선택 가능한 메뉴 표시
                if (totalMoney >= 1000)
                    System.out.print("메뉴를 선택하세요.\n[반환:0, 생수:1, 콜라:2, 쥬스:3] : ");
                else if (totalMoney >= 800)
                    System.out.print("메뉴를 선택하세요.\n[반환:0, 생수:1, 콜라:2] : ");
                else if (totalMoney >= 400)
                    System.out.print("메뉴를 선택하세요.\n[반환:0, 생수:1] : ");
                else
                    System.out.println("선택할 수 있는 메뉴가 없습니다. 돈을 더 넣으세요.");
                
                // 메뉴 선택
                if (totalMoney >= 400) {
                    yourChoice = objDrink.nextInt();
                }
                
                switch (yourChoice) {
                    case 0:
                        System.out.println("잔액 " + totalMoney + "원이 반환되었습니다. 잘 가세요.");
                        totalMoney = 0;  // 잔액 재계산
                        break;
                    case 1:
                        System.out.println("생수를 선택하셨네요^^ 여기 있어요.");
                        totalMoney = totalMoney - 400;  // 잔액 재계산
                        break;
                    case 2:
                        System.out.println("코카콜라~");
                        totalMoney -= 800;  // 잔액 재계산
                        break;
                    case 3:
                        System.out.println("오렌지 주스 받으세요.");
                        totalMoney -= 1000;  // 잔액 재계산
                        break;
                }
                // 잔액 표시
                System.out.println("현재 잔액은 " + totalMoney + "원입니다.");
            }
        }
    }
}
cs


+ Recent posts