본문 바로가기

Programming/국비학원

220425 - do while, 참조, 비트 이동 연산자, 삼항 연산자, 배열, 향상된 for문, 정렬

do while 반복문

자주 쓰이지는 않음

선수행 후조건 => 우선 do 문 수행하고 while문 조건 틀리면 탈출 (cf. for, while : 조건 만족 후 수행)

 

 

  •  
1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
        int i=1;
        int sum=0;
        do {
            sum+=i;
            i++;    
        }while(i<=100);   
        System.out.println("1~100: "+sum);
    }
cs

//

1~100: 5050

 

 

 

참조

: 직접 값이 들어있지 않고 값이 있는 주소를 가리키는 것 ex. 배열 타입, 열거 타입, 클래스, 인터페이스

 

 

  • 메모리 공간

스택 영역 : 공간에 직접 할당되는 값들 (int)

힙 영역 : 주소 가리키는 참조값들 (String)

 

=> 참조값은 변수(객체 주소값)가 스택에 생성, 객체는 힙에 생성됨

 

 

  • 메모리 사용 영역

1. 메소드 영역

 

2. 힙 영역

 

3. JVM 스택 영역

 

 

 

  • 틀린 예시

public static void main(String[] args) {
String str1= "김철수";
String str2= "김철수";
if (str1==str2) {    //주소값 비교함
System.out.println("두 이 같음");    //주소값이 같음
} else {
System.out.println("두 이 다름");
}
}
}


=> String에는 값이 아닌 값의 주소가 저장됨 

 

 

  • 옳은 예시

public static void main(String[] args) {
String str1= "김철수";
String str2= "김철수";
if (str1==str2) {
System.out.println("str1과 str2는 참조가 같음");
} else {
System.out.println("str1과 str2는 참조가 다름");
}
if (str1.equals(str2)) {   //주소에서 값을 직접 가져옴
System.out.println("같은 문자열임");
} else {
System.out.println("다른 문자열임");
}
}

 

 

cf. int
int num1=20;
int num2=30;
if(num1==num2){
~같은 숫자임~
} else {
~다른 숫자임~
}

 

 

  •  

public static void main(String[] args) {
String str1= "김철수";
String str2= "김철수";
if (str1==str2) {
System.out.println("str1과 str2는 참조가 같음");
} else {
System.out.println("str1과 str2는 참조가 다름");
}
if (str1.equals(str2)) {
System.out.println("같은 문자열임");
} else {
System.out.println("다른 문자열임");
}
String str3 = new String("김철수");
String str4 = new String("김철수");    //new : 새로운 값 창조
if (str3==str4) {    //참조 비교
System.out.println("str1과 str2는 참조가 같음");
} else {
System.out.println("str1과 str2는 참조가 다름");
}
if (str3.equals(str4)) {    //값 내용 비교
System.out.println("같은 문자열임");
} else {
System.out.println("다른 문자열임");
}
}
//
str1과 str2는 참조가 같음
같은 문자열임
str3과 str4는 참조가 다름
같은 문자열임

 

 

 

비트 이동(shift) 연산자 

<<, >> : 숫자, 방향대로 값 이동 (이진수 연산)

 

  •  

int number=1;    //0000 0001
int result = number << 3 ;    // 0000 1000 => 8
System.out.println(result);
//
8

 

 

  •  

int number=8;    //0000 1000
int result = number >> 3 ;    //0000 0001
//
1

 

 

※ 데이터타입 및 이진수 연산

byte (1byte) : -128 ~ 127
short (2byte) : -32768 ~ 32767

 

=> 연산 시 컴퓨터는 inverter 사용

=> 5-2 = 0101-0010 => inverter (뺄 값 오른쪽에서부터 훑다가 1 나온 다음부터 반대로 invert)

=> 0101+1110 => 0011 (오버플로우 계산 안 함) = 3

 

1000 0000 (128) => 1000 0000 (-128)

0111 1111 (127) => 1000 0001 (-127)

 

 

 

삼항 연산자

(조건)?값 or 연산식: or 연산식 => 조건 참이면 ? 뒤, 거짓이면 : 뒤 수행

 

cf. 단항 연산자(++ --) / 이항 연산자(+ - * /)

 

  •  

int num1=50;
int num2=70;
int max = (num1>num2)?num1:num2;
System.out.println("두 수 중 큰 값은 "+max+"입니다");
//
70

 

 

 

배열 (Array)

반복문과 잘 어울림

 

  •  
1
2
3
4
5
6
7
8
9
10
11
    public static void main(String[] args) {
//        int score1=70;
//        int score2=90;
//        int score3=96;
//        int score4=85;
//        ...
//        int total=score1+score2+score3+score4..
 
        int[] scores = {78,96,80,63,86};    //int scores[] 도 가능
        System.out.println(scores[0]);        
    }
cs

//

78

 

 

  • 반복문
1
2
3
4
5
6
public static void main(String[] args) {
int[] scores = {78,96,80,63,86};   //배열의 초기화
        for (int i=0;i<scores.length;i++) {
            System.out.println(scores[i]);
        }
    }
cs

//

78
96
80
63
86

 

 

  • 초기값

int[] scores = new int[5];    //5개 값 가지는 배열 생성  //에러X=> 배열은 생성과 동시에 초기값 정해짐
for (int i=0;i<scores.length;i++) {
System.out.println(scores[i]);
}
}
//
0
0
0
0
0

 

 

cf. int
int num1;
sysout "num1"
=> 값 지정 안돼 에러

 

 

 

향상된 for문

배열과 쓰임

 

  •  

for(타입 변수:배열이름) {
반복할 내용
}

 

 

  •  
1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
        int[] scores = {78,80,90,75,60};
        int sum=0;
        double avg;
        for (int score:scores) {
            sum+=score;
        }
        avg=(double)sum/scores.length;
        System.out.println("총점 : "+sum);
        System.out.println("평균 : "+avg);
}
cs

//
총점 : 383
평균 : 76.6

 

 

 

정렬 (sort)

 : 무질서한 자료를 원하는 순서대로 재배열

 

1. 오른차순(Ascending) : 작은 것 -> 큰 것
2. 내림차순(Descending) : 큰 것 -> 작은 것

 

 

 

 

 

//

 

  • numbergame 입력값 제한 추가
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
import java.util.Scanner;
 
public class NumberGame {
 
    public static void main(String[] args) {
        System.out.println("** 1~100 사이 숫자 맞추기 **");
        int comNum= (int) (Math.random()*100)+1;
        int count = 0
        Scanner sc = new Scanner(System.in);
        int myNum;
        while(true) {   
            System.out.print("숫자 입력>> ");
            myNum = sc.nextInt();
            if(myNum<=100 && myNum>=1) {
                count++;
                if (myNum > comNum) {
                    System.out.println("당신의 숫자가 커요. 좀 더 작은 수를 넣어보세요");
                } else if (myNum < comNum ) {
                    System.out.println("당신의 숫자가 작아요. 좀 더 큰 수를 넣어보세요");
                } else {System.out.println("탈출하셨습니다."+ count);
                    break;
                    }
            } else {
                System.out.println("1부터 100 사이 숫자만 입력하세요");
            }
       }//while문
        System.out.println("게임이 종료되었습니다.");
    }
}
cs

 

 

  • whileex2 입력값 제한 + 범위 벗어나면 입력문구 다시 뜨게 하기
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
import java.util.Scanner;
 
public class whileEx2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        boolean run = true;
        while (run) {
            System.out.print("행운의 숫자 입력>> ");
            int myNum = sc.nextInt();
            int count = 0;
            int dice;
            if(myNum<=6 && myNum>=1) {
                while (true) {
                    count++;
                    dice = (int) (Math.random()*6+1);
                    System.out.println(dice);
                    if (myNum==dice) {
                        run=false;
                        break;
                    }
                    }//while문
                if (count<=6) {
                    System.out.println("그래도 확률이 살아있군요");
                } else {
                        System.out.println("확률이 바닥이군요");
                }
            } else {
                System.out.println("주사위번호는 1부터 6까지의 숫자입니다.");
                System.out.println("다시 입력해보세요");
            }
        }
    }
}
cs

 

※ 백엔드 => for보다 while문 자주 씀 (몇 회 반복하는지 정확히 지정 안 해도 돼서)

 

 

  • do while
1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
        System.out.println("메시지를 입력하세요");
        System.out.println("프로그램을 종료하려면 q를 입력하세요");
        String input;    //String: 참조타입
        Scanner sc = new Scanner(System.in);
        
        do {
            System.out.print("입력 내용>> ");
            input = sc.nextLine();    //String타입 입력값 받음 (cf.nextInt)
            System.out.println("당신이 입력한 내용 : "+input);
        } while (!input.equals("q"));     // String => equals 사용 (==와 같음) //q 아닌 동안 반복
        System.out.println("프로그램 종료");
}
cs

 

 

  • 문제: 총점, 평균(소수점까지) 구하기

int[] scores = {85,96,60,85,77};

 

=>

1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) {
        int[] scores = {85,96,60,85,77};
        int sum = 0;
        double avg;
        for (int i=0;i<scores.length;i++) {
            sum+=scores[i];
        }
        avg = (double)sum/scores.length;    //형변환
        System.out.println(sum);
        System.out.println(avg);
}
cs

//
403
80.6

 

 

  • 문제: 짝수만 구하기

int[] nums = {45,2,36,12,80,35,16,71,42};

답: 짝수의 합 = ?

 

=>

1
2
3
4
5
6
7
8
9
10
    public static void main(String[] args) {
        int[] nums = {45,2,36,12,80,35,16,71,42};
        int sum=0;
        for (int i=0;i<nums.length;i++) {
            if (nums[i]%2==0) {
                sum+=nums[i];
            }
        }
        System.out.println(sum);
    }
cs

 

 

  • 문제: 시험점수 배열 => 합격자 수 구하시오.

int[] scores = {78,96,85,60,90,82,70,83,55,73};

조건: 80점 이상
답: 합격자수=5

 

=>

1
2
3
4
5
6
7
8
9
10
    public static void main(String[] args) {
        int[] scores = {78,96,85,60,90,82,70,83,55,73};
        int count=0;
            for (int i=0;i<scores.length;i++) {
                if (scores[i]>=80) {
                    count++;
                }
            }
    System.out.println("합격자 수 = "+count);
    }
cs

 

 

  • 메인 메소드

public static void main(String[] args) {
if (args.length==2) {
System.out.println(args[0]);
System.out.println(args[1]);
} else {
System.out.println("매개변수 값이 없습니다");
}
}
//run configuration- 매개변수 두개 입력

=>
김철수
이영희

 

 

  • 메인메소드2
1
2
3
4
5
6
7
8
9
10
    public static void main(String[] args) {
        if (args.length==2) {
            int num1 = Integer.parseInt(args[0]);    
//Integer 클래스-parseInt 메소드 구현  //문자("")를 정수(74)로 변환
            int num2 = Integer.parseInt(args[1]);
            int result = num1+num2;
            System.out.println("두 수의 합 = "+result);
        } else {
            System.out.println("매개변수 값이 없습니다");
        }
    }
cs

//run config => 숫자 두개 입력

두 수의 합 = 159