JavaSE

08일차_참조형, 배열

알 수 없는 사용자 2015. 6. 21. 07:13

-------------------------------
참조형 (Reference type)

1. 객체의 주소를 저장.

2. 메모리 운영은 stack, heap 영역을 나눠서 운영되고 있습니다.
stack 영역에는 크기가 작고, 규격화된 데이터를 취급합니다.
heap 영역에는 크기가 크고, 비정형 데이터를 취급합니다.
stack  영역의 데이터는 바로 읽고, 쓰기가 가능하지만,
heap 영역의 데이터는 stack 영역의 참조주소를 통해서 읽고, 쓰기가 가능합니다.

3. 자료형 선언시

기본형은
자료형 변수 = 값;

참조형은
자료형 변수 = new 자료형();

배열(참조형)은
자료형[] 변수 = new 자료형[크기];

라고 선언합니다.


--------------------------------
배열(Array)

1. 같은 자료형을 가진 변수들의 집합체.

2. 인덱스를 사용해서 구분. 예를 들어, 변수[0], 변수[1], ...

3. 사용하기 전에 배열의 크기를 지정해야 한다. 배열 선언(생성)시 크기 지정.
- 배열 선언 기본 형식

자료형[] 변수명;
변수명 = new 자료형[크기];

자료형[] 변수명 = new 자료형[크기];


예를 들어, 국어, 영어, 수학 점수를 저장하는 변수 확보.

배열을 사용하지 않는 경우는 아래와 같다.
int kor=0;
int eng=0;
int mat=0;

배열을 사용하는 경우는 아래와 같다. 자동 초기화 지원됩니다.
int[] subjects = new int[3];

subjects[0], subjects[1], subjects[2] 를 사용해서 점수 저장.
배열의 인덱스를 이용해서 반복문 지정이 가능합니다.


4. 배열 변수는 자동 초기화를 지원하는데 자료형의 기본값은
정수형인 경우는 0, 실수형인 경우는 0.0, 참조형인 경우는 null로 초기화 됩니다.

5. 배열의 변수는 사용자가 직접 초기화할 수 있습니다.
자료형[] 변수 = {데이터1, 데이터2, ...};


//Sample50.java
package com.test;

public class Sample50 {

 public static void main(String[] args) {
  //일반적인 변수 선언 및 초기화
  //기본자료형 변수;
  //변수 = 값;
  int a;
  a = 10;
  System.out.println(a);
  
  //배열(참조형) 선언 및 초기화1
  //인덱스는 0부터 표기
  //배열은 자동으로 초기화가 진행된다
  //초기값은 자료형에 의해서 결정된다
  //자료형[] 변수 = new 자료형[크기];
  //변수[인덱스] = 값;
  int[] b = new int[10];
  b[0] = 10;
  b[1] = 20;
  //...
  b[9] = 100;
  //b[10] = 110; //->X
  
  System.out.println(b[0]);
  System.out.println(b[1]);
  //...
  System.out.println(b[9]);
  
  //b.length 에서 length 는 배열의 크기를 반환
  for(int c=0; c<b.length; ++c) {
   System.out.println(b[c]);
  }
  
  
  //배열 선언 및 초기화2
  int[] d = {10, 20, 30, 40, 50};
  for(int c=0; c<d.length; ++c) {
   System.out.println(d[c]);
  }  

 }

}

 

 

월의 마지막 날짜 출력하는 경우(배열 사용 전)
//Sample36.java
package com.test;

import java.util.Scanner;

public class Sample36 {

 public static void main(String[] args) {
  
  //배열 사용 전 - 월별 마지막 날짜 확인
  //m1, m2, m3, ... -> m변수  X
  //m[0], m[1], m[2],... -> m[변수] O
  int m1 = 31;  
  int m2 = 28;
  int m3 = 31;
  int m4 = 30;
  int m5 = 31;
  int m6 = 30;
  int m7 = 31;
  int m8 = 31;
  int m9 = 30;
  int m10 = 31;
  int m11 = 30;
  int m12 = 31;
  
  Scanner sc = new Scanner(System.in);
  System.out.print("월(1~12)?");
  int month = sc.nextInt();
  sc.close();

  int result = 0;
  switch (month) {
  case 1: result = m1; break;
  case 2: result = m2; break;
  case 3: result = m3; break;
  case 4: result = m4; break;
  case 5: result = m5; break;
  case 6: result = m6; break;
  case 7: result = m7; break;
  case 8: result = m8; break;
  case 9: result = m9; break;
  case 10: result = m10; break;
  case 11: result = m11; break;
  case 12: result = m12; break;
  }
  
  System.out.printf("%d 월 : %d 일", month, result);
  

 }

}

 

//Sample51.java
package com.test;

import java.util.Scanner;

public class Sample51 {

 public static void main(String[] args) {
  
  //월별 마지막 날짜 출력
  /*
  1월달->31일
  2월달->28일
  ...
  12월달->31일
  */
  //m1, m2, m3, ... -> m변수  X
  //m[0], m[1], m[2],... -> m[변수] O
  int m31 = 31;  
  int m28 = 28;
  int m30 = 30;

  Scanner sc = new Scanner(System.in);
  System.out.print("월(1~12)?");
  int month = sc.nextInt();
  sc.close(); 
  
  int result = 0;
  switch (month) {
  case 1: case 3: case 5: case 7:
  case 8: case 10:
  case 12: result = m31; break;
  case 4: case 6: case 9:
  case 11: result = m30; break;
  case 2: result = m28; break;
  }
  
  System.out.printf("%d 월 : %d 일", month, result);
  
  
 }

}

 

 


월의 마지막 날짜 출력하는 경우(배열 사용 후)
//Sample52.java
package com.test;

import java.util.Scanner;

public class Sample52 {

 public static void main(String[] args) {
  //월별 마지막 날짜 출력
  /*
  1월달->31일
  2월달->28일
  ...
  12월달->31일
  */
  int[] m = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  
  //int month = 1;
  //m[month-1] -> month[0] -> 31 -> 1월달 날짜
  
  Scanner sc = new Scanner(System.in);
  System.out.print("월(1~12)?");
  int month = sc.nextInt();
  sc.close(); 
  
  System.out.printf("%d 월 : %d 일", month, m[month-1]);
  
 }

}

 


문제) 가위, 바위, 보 게임을 user1, user2의 입력(1~3)을 받아서, 승자 출력.
1->가위, 2->바위, 3->보 출력되도록 한다. 배열 이용.
user1의 선택(1~3)?1
user2의 선택(1~3)?2

user1: 가위
user2: 바위
승자 -> user2


//Sample53.java
package com.test;

import java.util.Scanner;

public class Sample53 {

 public static void main(String[] args) {
  
  //입력 과정 -------------
  Scanner sc = new Scanner(System.in);
  System.out.print("user1의 선택(1~3)?");
  int user1 = sc.nextInt();
  System.out.print("user2의 선택(1~3)?");
  int user2 = sc.nextInt();
  sc.close();
  
  //처리 과정 -------------
  int s = 0;
  if (user1 == user2) {
   s = 0;
  } else {
   s = ((user1%3) == ((user2+1)%3))?1:2;
  }  
  
  //출력 과정 -------------
  String[] result = {"비겼습니다.", "user1 승!", "user2가 이겼습니다."};
  String[] array = {"가위", "바위", "보"};
  System.out.printf(" user1:%s %n user2:%s %n 승자=>%s %n"
     , array[user1-1]
     , array[user2-1]
     , result[s]);

 }

}

 

 


-----------------------------------------------------------------


여러개의 수 중에서 가장 작은 수만 출력하는 프로그램 작성. (배열 사용)
int[] a = {6, 5, 8, 1, 2, 9, 3, 4, 7, 0};

//Sample54.java
package com.test;

public class Sample54 {

 public static void main(String[] args) {

  /*
  여러개의 수 중에서 가장 작은 수만 출력하는 프로그램 작성. (배열 사용)
  int[] a = {6, 5, 8, 1, 2, 9, 3, 4, 7, 0};
  */
  
  //가장 작은 값 찾는 과정
  //1. 첫 번째 값->임시변수
  //2. 임시변수의 값과 두 번째 이후의 값들을 비교 -> 반복문
  //3. 비교 결과 작은 값이 있으면 임시변수에 저장
  //4. 비교가 끝나면 임시변수의 값 출력
  
  int[] a = {6, 5, 8, 1, 2, 9, 3, 4, 7, 0};
  
  int temp = a[0];
  for (int b=1; b<a.length; ++b) {
   if (temp > a[b]) {
    temp = a[b];
   }
  }
  System.out.printf("min:%d %n", temp);

 }

}

 

 

여러개의 수 중에서 가장 큰 수만 출력하는 프로그램 작성. (배열 사용)
int[] a = {6, 5, 8, 1, 2, 9, 3, 4, 7, 0};

//Sample55.java
package com.test;

public class Sample55 {

 public static void main(String[] args) {

  /*
  여러개의 수 중에서 가장 큰 수만 출력하는 프로그램 작성. (배열 사용)
  int[] a = {6, 5, 8, 1, 2, 9, 3, 4, 7, 0};
  */
  
  //가장 큰 값 찾는 과정
  //1. 첫 번째 값->임시변수
  //2. 임시변수의 값과 두 번째 이후의 값들을 비교 -> 반복문
  //3. 비교 결과 큰 값이 있으면 임시변수에 저장
  //4. 비교가 끝나면 임시변수의 값 출력
  
  int[] a = {6, 5, 8, 1, 2, 9, 3, 4, 7, 0};
  
  int temp = a[0];
  for (int b=1; b<a.length; ++b) {
   if (temp < a[b]) {
    temp = a[b];
   }
  }
  System.out.printf("max:%d %n", temp);

 }

}

 

 

 

 


외부에서 숫자 n개를 입력 받아서 가장 작은 수만 출력하는 프로그램 작성.
(배열 사용)
실행 예)
입력 범위(2~n)?3
정수1?10
정수2?30
정수3?20

입력 받은 정수 3개: 10 30 20
가장 작은 수 출력 : 10

//Sample56.java
package com.test;

import java.util.Scanner;

public class Sample56 {

 public static void main(String[] args) {
  
  //외부 입력 -> 배열에 저장
  //1. 배열의 크기 결정 -> n
  //2. 크기에 맞는 숫자(n개)를 입력 받는다.
  //3. 입력 받은 숫자들을 배열에 저장.
  //-> 배열에 순차적으로 입력되도록 한다.
  //-> 반복문
  //-> 반복횟수? n번

  //입력 과정 ---------------------------
  Scanner sc = new Scanner(System.in);
  System.out.print("입력범위(2~n)?");
  int n = sc.nextInt();
  int[] a = new int[n];
  for (int b=0; b<n; ++b) {
   System.out.printf("숫자%d?", (b+1));
   a[b] = sc.nextInt();
  }
  sc.close();
  
  //처리과정
  int temp = a[0];
  for (int b=1; b<a.length; ++b) {
   if (temp > a[b]) {
    temp = a[b];
   }
  }
  
  //출력과정
  System.out.printf("가장 작은 수 출력 : %d %n", temp);
  

 }

}

 

 


------------------------------------------


문제) 외부에서 숫자 n개를 입력 받고, 1부터 입력된 숫자까지 출력하는 프로그램 작성. (배열 사용)
실행 예)
입력 범위(2~n)?3
정수1?10
정수2?30
정수3?20

1 2 3 4 ... 10
1 2 3 4 ....      30
1 2 3 4 .....  20

 

//Sample57.java
package com.test;

import java.util.Scanner;

public class Sample57 {

 public static void main(String[] args) {

  //외부에서 숫자 n개를 입력 받고,
  //->배열에 저장
  //1부터 입력된 숫자까지 출력

  /*
  int n = 10;
  for (int a=1; a<=n; ++a){
   System.out.printf(" %d", a);
  }
  System.out.println();
  */
  
  //입력 과정 ---------------------
  Scanner sc = new Scanner(System.in);
  System.out.print("입력 범위(2~n)?");
  int n = sc.nextInt();
  
  int[] a = new int[n];
  
  for (int b=0; b<n; ++b) {
   System.out.printf("숫자%d?", (b+1));
   a[b] = sc.nextInt();
  }
  
  sc.close();
  
  //출력 과정 ------------------
  for (int d=0; d<n; ++d) {
   for (int c=1; c<=a[d]; ++c){
    System.out.printf(" %d", c);
   }
   System.out.println();
  }
  
  
 }

}

 

 

문제) 외부에서 숫자 n개를 입력 받고, 1부터 입력된 숫자까지 출력하고, 그 숫자들의 합을 같이 출력하는 프로그램 작성. (배열 사용)
실행 예)
입력 범위(2~n)?3
정수1?10
정수2?30
정수3?20

1 2 3 4 ... 10  => 55
1 2 3 4 ....      30 => ??
1 2 3 4 .....  20 => ??

 

//Sample58.java
package com.test;

import java.util.Scanner;

public class Sample58 {

 public static void main(String[] args) {

  //외부에서 숫자 n개를 입력 받고,
  //->배열에 저장
  //1부터 입력된 숫자까지 출력
  //->합 까지 출력

  /*
  int n = 10;
  for (int a=1; a<=n; ++a){
   System.out.printf(" %d", a);
  }
  System.out.println();
  */
  
  //입력 과정 ---------------------
  Scanner sc = new Scanner(System.in);
  System.out.print("입력 범위(2~n)?");
  int n = sc.nextInt();
  
  int[] a = new int[n];
  
  for (int b=0; b<n; ++b) {
   System.out.printf("숫자%d?", (b+1));
   a[b] = sc.nextInt();
  }
  
  sc.close();
  
  //처리 과정 ------------------
  //-> 배열에 저장된 숫자들의 합 계산
  int[] sum = new int[n];
  for (int d=0; d<n; ++d) {
   for (int c=1; c<=a[d]; ++c){
    sum[d] += c;
   }
  }
  
  //출력 과정 ------------------
  for (int d=0; d<n; ++d) {
   for (int c=1; c<=a[d]; ++c){
    System.out.printf(" %d", c);
   }
   System.out.printf(" => %d %n", sum[d]);
  }
    
 }

}

 


문제) 외부에서 숫자 n개를 입력 받고, 입력된 숫자들의 팩토리얼(n!) 값 출력.
배열 이용. 곱하기 연산의 초기값은 1로 지정해야 한다.
입력 범위(2~n)?3
정수1?2
정수2?3
정수3?4

2! -> ???
3! -> ???
4! -> ???

 

//Sample59.java

package com.test;

import java.util.Scanner;

public class Sample59 {

 public static void main(String[] args) {

  //외부에서 숫자 n개를 입력 받고,
  //->배열에 저장
  //입력된 숫자들의 팩토리얼(n!) 값 출력

  /*
  int n = 10;
  int pact = 1;
  for (int a=1; a<=n; ++a){
   pact *= a;
  }
  System.out.println(pact);
  */
  
  //입력 과정 ---------------------
  Scanner sc = new Scanner(System.in);
  System.out.print("입력 범위(2~n)?");
  int n = sc.nextInt();
  
  int[] a = new int[n];
  
  for (int b=0; b<n; ++b) {
   System.out.printf("숫자%d?", (b+1));
   a[b] = sc.nextInt();
  }
  
  sc.close();
  
  //처리 과정 ------------------
  //-> 배열에 저장된 숫자들의 팩토리얼(n!) 계산
  int[] pact = new int[n];
  for (int b=0; b<n; ++b) {
   pact[b] = 1;
   for (int c=1; c<=a[b]; ++c){
    pact[b] *= c;
   }
  }
  
  //출력 과정 ------------------
  for (int b=0; b<n; ++b) {
   System.out.printf("%d! => %d %n", a[b], pact[b]);
  }
  
 }

}

 

 

 

문제) 외부에서 숫자 n개를 입력 받고, 가장 작은 값, 가장 큰 값 출력.
배열 이용.

입력 범위(2~n)?3
정수1?10
정수2?30
정수3?20

가장 작은 수 출력 : 10
가장 큰 수 출력 : 30

 

package com.test;
import java.util.*;
public class work5 {
 public static void main(String ar[]) {
/*  문제) 외부에서 숫자 n개를 입력 받고
 *   가장 작은 값, 가장 큰 값 출력.
  배열 이용.

  입력 범위(2~n)?3
  정수1?10
  정수2?30
  정수3?20

  가장 작은 수 출력 : 10
  가장 큰 수 출력 : 30  
*/
  Scanner sc = new Scanner(System.in);
  System.out.print("숫자를 입력 하세요 = ");
  int number = sc.nextInt();
  int [] array = new int[number];
  for(int a = 0; a<number; ++a) {
   System.out.printf("정수%d =", a+1);
   array[a] = sc.nextInt();
  }sc.close();
  //입력과정---------------------------------------
  
  int Min = array[0], Max = array[0];
  
  for(int b = 1; b<number; ++b){
   //가장 작은값을 찾을떄.
   if (Min > array[b]) {
    Min = array[b];
   } else if(Max < array[b]){
    Max = array[b];    
   }
  }
  
  //처리과정----------------------------------------
  System.out.printf("min = %d max = %d %n",Min, Max);
 }
}


문제) 외부에서 숫자 n개를 입력 받고, 숫자들의 합, 평균 출력.
배열 이용.

입력 범위(2~n)?3
정수1?10
정수2?30
정수3?20

합 출력 : ????
평균 출력 : ????

 

package com.test;
import java.util.*;
public class work6 {
 public static void main(String ar[]) {
/* 문제) 외부에서 숫자 n개를 입력 받고, 숫자들의 합, 평균 출력.
 배열 이용.

 입력 범위(2~n)?3
 정수1?10
 정수2?30
 정수3?20

 합 출력 : ????
 평균 출력 : ????
*/
  Scanner sc = new Scanner(System.in);
  System.out.print("숫자를 입력하세요 = ");
  int number = sc.nextInt();
  
  int [] array = new int[number];
  for(int a = 0; a<number; ++a){
   System.out.printf("정수%d = ", (a+1));
   array[a] = sc.nextInt();
  }sc.close();
  //입력과정 --------------------------------------
   int sum = 0;
   int d = 0;
   for(int a = 0; a <number; ++a) {
    sum += array[a];
   }
   d = sum / number;
   
  //과정입력----------------------------------------
   System.out.printf("합은 = %d %n", sum);
   System.out.printf("평균은 = %d", d);
 }
}


문제) 외부에서 숫자 n개를 입력 받고, 숫자만큼의 별문자(*) 출력.
배열 이용.

입력 범위(2~n)?3
정수1?10
정수2?20
정수3?30

********** -> 10
******************** -> 20
****************************** -> 30

 

package com.test;
import java.util.*;
public class work7 {
 public static void main(String ar[]) {
/*  문제) 외부에서 숫자 n개를 입력 받고, 숫자만큼의 별문자(*) 출력.
  배열 이용.

  입력 범위(2~n)?3
  정수1?10
  정수2?30
  정수3?20

  ********** -> 10
  ******************** -> 20
  ****************************** -> 30
*/
  Scanner sc = new Scanner(System.in);
  
  System.out.print("W.N = ");
  int Number = sc.nextInt();
  
  int [] array = new int [Number];
  for(int i = 0; i <Number; ++i) {
  System.out.printf("숫자%d = ", (i+1));
  array[i] = sc.nextInt();
  }sc.close();
  //-------------------------------------------입력
  
  for(int i = 0; i <=Number; ++i){
   for(int j = 1; j<=array[i]; ++j){
    System.out.printf("*");
   }System.out.println();
  }
  //--------------------------------------------처리
  
 }
}

 


----------------------------------
요약

1. 참조형 자료형의 특징
- 기본자료형 -> stack
- 참조자료형 실제 데이터 -> heap
, 참조자료형의 참조주소 -> stack

2. 배열
- 같은 자료형, 변수의 집합체.
- 인덱스 지원.
- 기본 형식
자료형[] 변수명 = new 자료형[크기];
자료형[] 변수명 = {데이터1, 데이터2, ...};
- 인덱스 사용 예
for (int i=0; i<array.length; i++) {
 System.out.printf("%d ", array[i]);
}

-----------------------------------------