본문 바로가기

Programming/국비학원

220428 - 배열 복사, 열거 타입

배열 복사
  • 배열 (참조 타입)

같은 타입 데이터를 연속된 공간에 나열하고, 각 데이터에 인덱스 부여하는 구조

 

 

  • 틀린 예시

public static void main(String[] args) {
int[] nums1 = {10,20,30,40,50};    //nums1, 즉 배열 자체가 주소번지로 이뤄진 참조타입
int[] nums2 = new int[5];    //참조배열 선언 : 0으로 채워짐
nums2=nums1;   //nums2는 nums1이 가리키는 주소 똑같이 가리킴
System.out.println(nums2[2]); 
}

//30

=> 값이 아닌 주소값(참조값) 복사한 것

 

 

  • 옳은 예시

public static void main(String[] args) {
int[] nums1 = {10,20,30};
int[] nums2 = new int[5];

for (int i=0;i<nums1.length;i++) {
nums2[i]=nums1[i];    //참조값이 아닌 값의 내용 가져옴
}

for (int i=0; i<nums2.length;i++) {
System.out.print(nums2[i]+" ");
}
}
//
10 20 30 0 0 

 

 

  • 옳은 예시 - Arraycopy 메소드 사용

public static void main(String[] args) {
int[] nums1 = {10,20,30};
int[] nums2 = new int[5];

System.arraycopy(nums1, 0, nums2, 0, nums1.length);    
//nums1[0]부터 복사 -> nums2[0]으로 3개 붙여넣기

for (int i=0; i<nums2.length;i++) {
System.out.print(nums2[i]+" ");
}
}
//
10 20 30 0 0 

 

 

  • String 배열 복사 - 얕은 복사(참조 / 원본 or 복사본 변경되면 연동됨)

public static void main(String[] args) {
String[] str1 = {"김철수","이영희","홍길동"};
String[] str2 = new String[5];

System.arraycopy(str1, 0, str2, 0, str1.length);

//string 자체가 참조값임 => 참조의 참조


for (int i=0; i<str2.length;i++) {
System.out.print(str2[i]+" ");
}
}
//
김철수 이영희 홍길동 null null  => string 배열의 기본값 : null

 

 

열거 타입 (enum)

: 고정값들 열거 -> 선택지 안에서 사용하도록 함

상수 대문자로 구성

 

  • enum 생성

public enum Week {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}

 

 

  • enum 활용
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
import java.util.Calendar;
 
public class EnumWeekEx1 {
 
    public static void main(String[] args) {
        Week today = null;
        Calendar cal = Calendar.getInstance();  
        int w=cal.get(Calendar.DAY_OF_WEEK);    //요일을 수로 환산
        switch(w) {
            case 1:
                today=Week.SUNDAY;
                break;
            case 2:
                today=Week.MONDAY;
                break;
            case 3:
                today=Week.TUESDAY;
                break;
            case 4:
                today=Week.WEDNESDAY;
                break;
            case 5:
                today=Week.THURSDAY;
                break;
            case 6:
                today=Week.FRIDAY;
                break;
            case 7:
                today=Week.SUNDAY;
                break;
        }
        System.out.println(today);
        if (today==Week.SUNDAY) {
            System.out.println("일요일이니 집에서 쉬세요.");
        }else {
            System.out.println("열심히 자바 공부합시다.");
        }
 
    }
 
}
cs

 

 

  • Calendar API 활용

public static void main(String[] args) {
Week today = null;    //Week : 열거타입(enum)
Calendar cal = Calendar.getInstance();
int y=cal.get(Calendar.YEAR);     //cal의 YEAR값만 가져와서 y 변수에 넣음
System.out.println(y);
int z=cal.get(Calendar.MONTH)+1  //이번 달
System.out.println(z);
int w=cal.get(Calendar.DAY_OF_WEEK);    //일요일 시작, 요일을 수로 환산
System.out.println(w);
}

//

2022

4

5

 

※ 날짜 해당하는 요일 계산
622 503 514 624
1       ~       12월

=> 12/25 => 25+4 = 29 = 7*4 +1 => 1 = 일요일
=> 5/5 => 0+5 => 5 = 목요일

=>
1월
일 월 화 수 목 금 토
                      1  = 6일 빔

 

 

 

 

 

////4장 복습

 

  • switch : 변수로 int, short, byte, char, string 가능 (double, float 불가)

 

  • 문제 : 3의 배수만 출력

public static void main(String[] args) {
int sum=0;
for (int i=3;i<=100;i+=3) {    //풀이2 : i 초깃값을 3으로 함
if (i%3==0) {
sum+=i;
}
}
System.out.println(sum);
}

 

 

  • 문제 : 주사위 2개 굴릴 때, 두 값을 더해 5가 될때까지 굴리기 (while)

1.

public static void main(String[] args) {
int dice1 = 0;
int dice2 = 0;
while (dice1 + dice2 !=5) {
dice1 = (int)(Math.random()*6)+1;
dice2 = (int)(Math.random()*6)+1;
System.out.println("("+dice1+","+dice2+")");
}
}

 

2.

public static void main(String[] args) {
int dice1;
int dice2;
while (true) {
dice1 = (int)(Math.random()*6)+1;
dice2 = (int)(Math.random()*6)+1;
System.out.println("("+dice1+","+dice2+")");
if (dice1+dice2==5) {
break;
}}}

 

 

  • 4x+5y=60 일 때 x, y의 값 (x, y는 자연수 1~10)

public static void main(String[] args) {
for (int x=1;x<=10;x++) {
for (int y=1;y<=10;y++) {
if ((4*x)+(5*y)==60) {
System.out.println("("+x+","+y+")");
}}}}

 

 

  • 출금, 예금 문제 +예금<출금 경우 제한

public static void main(String[] args) {

 

boolean run=true;
int balance=0;
Scanner sc = new Scanner(System.in);
int amount=0;

while(run) {
  System.out.println("1.예금 2.출금 3.잔고 4.종료");
  System.out.print("선택>> ");
  int num = sc.nextInt();
  switch(num) {
    case 1:
      //예금
      System.out.println("예금액>> ");
      balance+=sc.nextInt();
      break;

    case 2:
       //출금
      System.out.println("출금액>> ");
      amount = sc.nextInt();  
      if (amount>balance) {  
        System.out.println("잔액 부족");
       }else{
         balance-=amount;
       }
      break;
    case 3:
     //잔고
      System.out.println("잔고>> "+balance);
      break;
    case 4:
      run=false;
      break;
    default:
     System.out.println("1~4 사이 숫자를 입력하세요");
  }//switch

}//while
    System.out.println("프로그램 종료");
}