[220928] 클래스 변수, 메소드, 예외처리

황준하·2022년 9월 28일
0

◆ 클래스 변수와 클래스 메소드

▶ 클래스 변수

- static 변수 용어 정리

- 접근방법

- 예제 123

▶ 클래스 메소드

- 클래스 메소드에서 인스턴스 변수가 올수 없는 이유?

class AAA {
    int num = 0;
    static void addNum(int n) {
    num += n;
  }
}
  • static 함수 안에는 static 변수만 들어가야 한다. 인스턴스는 객체가 생성되기 전에 메모리에 올라가지 않기 때문에 에러가 발생한다.
  • 정리
    static이란 한번 먼저 올려서, 공유하는 변수이다.

- println

out은 클래스 System의 이름을 통해 접근하므로, 이는 System 클래스의 클래스 변수이름을 유추할 수 있다.

- 메인메소드가 static인 이유

  • static 인 이유
    인스턴스 생성과 관계없이 가장 먼저 호출되는 메소드이다.
  • public 인 이유
    main 메소드의 호출 명령은 외부로부터 시작되는 명령이다. 단순히 일종의 약속으로 이해해도 무방

◆ 예외처리

▶ 예외처리에 대한 이해

- 자바에서의 예외

  • 예외(Exception)
    단순한 문법 오류가 아닌 실행 중간에 발생하는 '정상적이지 않은 상황'을 뜻한다.
  • 예외처리
    자바는 예외처리 메커니즘을 제공한다.
  • 누가 에러를 처리하고 있는가?
public static void main(String[] args) {
 Scanner kb = new Scanner(System.in);
 System.out.print("a/b...a? ");
 int n1 = kb.nextInt(); // int형 정수 입력
 System.out.print("a/b...b? ");
 int n2 = kb.nextInt(); // int형 정수 입력
 System.out.printf("%d / %d = %d \n", n1, n2, n1 / n2);
 System.out.println("Good bye~~!");
} 

JVM이 처리해준다. 자바의 기본 예외처리 메커니즘은 문제가 발생한 지점에 대한 정보 출력과 프로그램 종료이다.

- 예외처리 try ~ catch

public class EmployeeTest {

	public static void main(String[] args) {
		try {
			int result = 10 / 0;
		} catch (ArithmeticException e) {
			e.printStackTrace();
			System.out.println("오류발생");
		} finally {
			System.out.println("try/catch 통과");
		}
	}

}
  • 객체생성없이 e.printStackTrace() 메서드를 사용할 수 있는 이유
    (ArithmeticException e) 에서 객체를 생성하지 않아도 e.printStackTrace() 메서드를 사용할 수 있다. JVM이 가능하게 해준다.
public class Example {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);

        try {

            System.out.print("a/b... a? ");
            int n1 = kb.nextInt();

            System.out.print("a/b... b? ");
            int n2 = kb.nextInt();

            System.out.printf("%d / %d = %d \n", n1, n2, n1 / n2);

        } catch (ArithmeticException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (InputMismatchException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
        	System.out.println(e.getMessage());
        }finally {
            System.out.println("무조건 실행");
        }

        System.out.println("Good bye~~!");

    }

}

- 예외처리 throws

- 예외 클래스 구분

- 예외처리를 프로그래머가 해야 하는 경우

- 기타

  • 디버깅 툴

▶ 과제

- 삽입정렬

private static int[] solution(int[] arr) {

		int j, tmp;
		for (int i = 1; i < arr.length; i++) {
			j = i - 1;
			tmp = arr[i];
			while (j >= 0) {
				if (arr[j] > tmp)
					arr[j + 1] = arr[j];
				else
					break;
				j--;
			}
			arr[j + 1] = tmp;
		}
		return arr;
	}

- Buyer 클래스

package java_0926;

public class EmployeeTest {

	public static void main(String args[]) {

		Buyer b = new Buyer();
		b.buy(new Tv());
		b.buy(new Computer());
		b.buy(new Tv());
		b.buy(new Audio());
		b.buy(new Computer());
		b.buy(new Computer());
		b.buy(new Computer());

		b.summary();

	}

}

class Buyer {
	int money = 1000;
	Product[] cart = new Product[3]; // 구입한 제품을 저장하기 위한 배열

	int i = 0; // Product배열 cart에 사용될 index

	void buy(Product p) {

		/*
		 * 
		 * (1) 아래의 로직에 맞게 코드를 작성하시오 . 1.1 가진 돈과 물건의 가격을 비교해서 가진 돈이 적으면 메서드를
		 * 
		 * 종료한다. 1.2 가진 돈이 충분하면, 제품의 가격을 가진 돈에서 빼고 1.3 장바구니에 구입한 물건을 담는다.(add
		 * 
		 * 메서드 호출 )
		 * 
		 */

	}

	void add(Product p) {

		/*
		 * 
		 * (2) 아래의 로직에 맞게 코드를 작성하시오. 1.1 i의 값이 장바구니의 크기보다 같거나 크면 1.1.1 기존의
		 * 
		 * 장바구니보다 2배 큰 새로운 배열을 생성한다. 1.1.2 기존의 장바구니의 내용을 새로운 배열에 복사한다. 1.1.3 새로운
		 * 
		 * 장바구니와 기존의 장바구니를 바꾼다. 1.2 물건을 장바구니(cart)에 저장한다. 그리고 i의 값을 1 증가시킨다.
		 * 
		 */

	} // add(Product p)

	void summary() {

		/*
		 * 
		 * (3) 아래의 로직에 맞게 코드를 작성하시오 . 1.1 장바구니에 담긴 물건들의 목록을 만들어 출력한다 . 1.2 장바구니에
		 * 
		 * 담긴 물건들의 가격을 모두 더해서 출력한다. 1.3 물건을 사고 남은 금액 를 출력한다(money).
		 * 
		 */

	} // summary()

}

class Product {

	int price; // 제품의 가격

	Product(int price) {

		this.price = price;

	}

}

class Tv extends Product {

	Tv() {

		super(100);

	}

	public String toString() {

		return "Tv";

	}

}

class Computer extends Product {

	Computer() {

		super(200);

	}

	public String toString() {

		return "Computer";

	}

}

class Audio extends Product {

	Audio() {

		super(50);

	}

	public String toString() {

		return "Audio";

	}

}

//[실행결과]
//
//잔액이 부족하여 Computer을/를 살 수 없습니다.
//구입한 물건 : Tv, Computer, Tv, Audio, Computer, Computer,
//
//사용한 금액 : 850
//남은 금액 : 150
//```
//
//### 풀이
//
//```
	void buy(Product p) {

		if (money < p.price) {

			System.out.println("잔액이 부족하여 " + p.toString() + "을/를 살 수 없습니다.");

			return;

		}

		else {

			money -= p.price;

			add(p);

		}

	}

	void add(Product p) {

		Product[] newCart = null;

		if (i >= cart.length) {

			newCart = new Product[cart.length * 2];

			/*
			 * for(int idx =0; idx < cart.length; idx++){
			 * 
			 * newCart[idx] = cart[idx];
			 * 
			 * }
			 */

			System.arraycopy(cart, 0, tmp, 0, cart.length);

			cart = newCart;

		}

		cart[i++] = p;

	}

void summary() {

	

	 int sum = 0;

	 System.out.print("구입한 물건: ");

	 for(int idx = 0; idx < i; idx++){

		 System.out.print(cart[idx].toString()+",");

		 sum += cart[idx].price;

	 }

	 System.out.println();

	 System.out.println("사용한 금액: " +sum);

	 System.out.println("남은 금액: " + money);

}

0개의 댓글