class Test4 {
	// 인스턴스 변수. 객체가 생성되어야 사용가능.
    // 객체가 생성될 때 ! 메모리가 할당된다.
    int a;
    private int b=10;
    
    // 클래스변수. 객체생성과 상관없이 사용가능.
    // 클래스가 로딩될 때 메모리 할당
    public static int c=100;
    
    // 인스턴스 메소드. 객체가 생성되어야 사용가능.
    public void print(){
    	System.out.println(a+ " : " +b + " : " +c);
    }
    
    // 클래스 메소드. 객체 생성과 상관없이 사용 가능.
    public static void write(){
    	// System.out.println(a); 컴파일 오류. 
        // 클래스 메소드에서는 인스턴스 변수나 인스턴스 메소드를 호출 할 수 없다.
        System.out.println(c)
    }

}

 

public class Ex04_class {

	public static void main(String[] args) {
    	System.out.println(Test4.c);
        // 클래스 메소드 접근
        // "클래스명.메소드명([인수])" 형식으로 접근
     	Test4.write();
        
        // 인스턴스 변수, 인스턴스 메소드는 객체 생성 후 접근
        Test4 tt = new Test();
        tt.a=50;
        tt.print();
        
        Test4 tt2 = new Test4();
        tt2.print();
            
    }

}

인스턴스 변수와 인스턴스 메소드

클래스 변수와 클래스 메소드의 차이를 알아보자

 

인스턴스 변수와 인스턴스 메소드는 객체 생성 후 접근이 가능하다.

메모리 할당이 되어있지 않기 때문이다.

 

클래스 변수와 클래스 메소드는 객체를 생성하지 않고 접근이 가능하다.

클래스가 로딩 될 때 메모리를 할당하기 때문이다.

public class Ex03_array {

	public static void main(String[] args){
    	int [][]a = {{10,20,30},{100,200,300}};
        int [][]b = new int[a.length][a[0].length];
        
        // 4번째 줄의 경우, a 배열 선언 및 메모리 할당, 값 입력까지 한 것
        // 5번째 줄의 경우, b 배열 선언 및 메모리 할당까지 한 것
        
        /* 1차원 배열의 경우 배열 복사
        System.arraycopy(a, 0, b, 0, a.length);         
        */
        
        // 2차원 배열의 값 복사
        // 10, 20, 30을 채우고 그 다음 행에 100, 200, 300을 채우는 것
        for(int i=0; i<a.length; i++){
        	System.arraycopy(a[i], 0, b[i], 0, a[i].length);
        }
        
        b[1][1] = 70;
        System.out.println(a[1][1]+ " : " +b[1][1]);
    
    }

}

public class Ex02_array {

	public static void main(String[] args){
    	int []a = new int[] {10,20,30};
        int []b = new int[a.length];
        
        System.arraycopy(a, 0, b, 0, a.length);
        // a의 배열의 0부터 길이까지 b배열에 복사
        
        System.out.println(a == b);
        // a배열과 b배열의 주소 비교 -> false
        
        System.out.println("a배열");
        for(int n: a)
        	System.out.print(n+"  ");
        System.out.println();
        
        System.out.println("b배열");
        for(int n: b)
        	System.out.print(n+"  ");
        System.out.println();
    
    	b[1] = 200;
        System.out.println(a[1]+" : "+b[1]);
    }

}

public class Ex01_array {

	public static void main(String[] args) {
    	int []a = new int[] {10,20,30};
        
        for(int i=0; i<a.length; i++){
        	System.out.print(a[i]+"  ");
        }
        System.out.println();
        
        int []b = new int[5];
        System.arraycopy(a, 0, b, 0, a.length);
        // arraycopy(원본배열, 본사시킬 원본 배열 시작위치, 대상배열, 복사시킬 위치, 복사할개수)
        
        for(int i=0; i<b.length; i++){
        	System.out.print(b[i]+"  ");
        }
        System.out.println();
        
        a = b;
        // b 배열의 주소를 a에게 할당.
        // 원래 a의 주소는 사라지게 된다. 
        
        for(int i=0; i<a.length; i++) {
        	System.out.print(a[i]+"  ");
        }
        
        System.out.println();    
    
    }

}

배열은 참조형 데이터타입이다.

배열은 초기화하지 않으면 0으로 초기화된다. 

b의 주소값을 a에게 옮겼기 때문에 원래 a가 가지고 있던 3개의 값을 저장한 주소는 찾을 수 없게 되므로 garbage collector의 회수 대상이 되어 사라진다.

import java.util.Arrays;

public class Ex05_bubble {

	public static void main(String[] args) {
		// Bubble sort
		int []num = new int[] {25,15,10,5,12,9,17,23,13,19};
		int t;
		
		System.out.print("Source data : ");
		for(int i=0; i<num.length; i++) {
			System.out.printf("%5d", num[i]);
		}
		System.out.println();
		
		// 정렬
		// 1회전 : (0:1)(1:2)(2:3)...(8:9)
		// 2회전 : (0:1)(1:2)(2:3)...(7:8)
		// 3회전 : (0:1)(1:2)(2:3)...(6:7)
		//		:
		// 9회전 : (0:1)
		
		for(int i=1; i<num.length; i++) { // i=0; i<9; i++ 9회전
			for(int j=0; j<num.length-i; j++) {
				if(num[j] > num[j+1]) { 
					t = num[j];
					num[j] = num[j+1];
					num[j+1] = t;
				}
			}
			System.out.println(i+"회전 : " + Arrays.toString(num));
			
		}
		
		System.out.print("Sort data : ");
		for(int i=0; i<num.length; i++) {
			System.out.printf("%5d", num[i]);
		}

	}

}

 

https://www.toptal.com/developers/sorting-algorithms

 

Sorting Algorithms Animations

Animation, code, analysis, and discussion of 8 sorting algorithms on 4 initial conditions.

www.toptal.com

public class Ex04_selection {

	public static void main(String[] args) {
		// Selection Sort
		int []num = new int[] {25,15,10,5,12,9,17,23,13,19};
		int t;
		
		System.out.print("Source data : ");
		for(int n: num) {
			System.out.printf("%5d", n);
		}
		System.out.println();
		
		// 정렬
		for(int i=0; i<num.length-1; i++) { // i=0; i<9; i++ 9회전
			for(int j=i+1; j<num.length; j++) {
				if(num[i] > num[j]) { // 부등호에 따라 오름차순, 내림차순
					t = num[i];
					num[i] = num[j];
					num[j] = t;
				}
			}
		}
		
		System.out.print("Sort data : ");
		for(int n: num) {
			System.out.printf("%5d", n);
		}
		System.out.println();
	}

}

Selection 정렬 : 가장 앞에 가장 작은 값을 놓는다.


50 25 60 35 40
1회전 : (1번째:2번째)(1번째:3번째)(1번째:4번째)(1번째:5번째)
25 : 50 / 25 : 60 /  25: 35 / 25 : 40
결과 : 25 50 60 35 40 
총 비교 횟수 n(n-1)/2
가장 쉬운 정렬 방식

 

로또 1~45까지 수중 서로 다른 6개의 수를 구매 갯수 만큼 생성하기.

 

import java.util.Scanner;

public class Ex03_Quiz {
	public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    int[] lotto = new int[6];
    int cnt;
    
    do {
    	System.out.print("구매 개수 ?");
        cnt=sc.nextInt();
    } while (cnt<1 || cnt>5);
    
    for(int i=1; i<=cnt; i++) { // 구매 개수
    	for(int j=0;j<lotto.length; j++){ // 1개를 구매했으면 6개 숫자가 나오고, 2개를 구매했으면 6개x2가 나옴
        	lotto[j] = (int)(Math.random() * 45) + 1; // 배열에 숫자를 넣음
         
            for(int k=0; k<j; k++){ // 숫자가 넣어져있는 배열
            //동일한 난수가 발생되는 경우 다시 추출
            	if(lotto[j]==lotto[k]){ // 그 넣어져있는 숫자가 다음 입력한 숫자와 같으면
                	j--; // 다시 추출
                    break;
                }
            }
        }
        
        System.out.printf(i+"번째 : ");
        for(int n : lotto) {
        	System.out.print(n+"  ")l
            } // 배열 출력
        System.out.println();
    }
    
    
    sc.close();
    }
}

5개의 점수(0~10)을 입력받아 최대점수와 최소점수를 뺀 합을 구하는 프로그램

배열을 활용해서 풀어보자

import java.util.Scanner;

public class Ex02_Quiz {
	public static void main(String[] args) {
    
    Scanner sc = new Scanner(System.in);
    int []score = new int[5];
    int max, min;
    int tot, result;
    
    // 5개의 점수 입력받기 
    // 점수는 0~10
    
    tot = 0;
    for(int i=0; i<5; i++){
    	do {
        System.out.print((i+1)+"번째 점수 : ");
    	score[i] = sc.nextInt();
    	} while (score[i]<0 || score[i]>10);
        tot+=score[i];
    }
    max = min = score[0]; 
    // 가장 처음에 입력받은 점수를 max와 min에 넣고 비교한다.
    for(int i=1; i<score.length; i++){
    	if(min>score[i]){
        	min = score[i];
        } else if(max<score[i]) {
        	max = score[i];
        }
    }
    
    result = tot - min - max;
    
    System.out.print("점수 리스트 : ");
    for(int n: score) {
    System.out.print(n+"  ");
    }
    System.out.print("\n취득 점수 : " + result);
    
    sc.close()
   
    }
}

+ Recent posts