package ex0727;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Ex110_tryResource {

	public static void main(String[] args) {
		int n;
		String s;

		// JDK 7.0 부터 가능
		// try~with~resource : 자동으로 resource가 close됨.
		try (Scanner sc = new Scanner(System.in)) { // DB에서 활용하면 편하다.
			System.out.println("나이 ? ");
			n = sc.nextInt();
			s = n >= 19 ? "성인" : "미성년자";
			System.out.println(s + " 입니다.");
			
		} catch (InputMismatchException e) {
			System.out.println("숫자만 입력 가능합니다.");
		}

		System.out.println("end...");

	}

}

try 에 스캐너를 넣어주면 마지막에 sc.close(); 를 안넣어도 느낌표가 뜨지 않으므로 사용시 편리하다. DB에서 사용하면 편하다고 하심. (아직 DB를 안배워서 잘 모르겠지만 그렇다고하심)..

package ex0727;

import java.util.Scanner;

public class Ex106_finally {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String[] ss = new String[3];
		int idx;
		String s;
		
		try {
			idx = 0;
			System.out.println("문자열 입력[종료:입력하지 않고 엔터]...");
			while( (s = sc.nextLine()).length() != 0 ) {
				ss[idx++] = s;
				System.out.print("문자열 입력 : "); // 예외 발생하면 실행 되지 않는다.
			}
		} catch (ArrayIndexOutOfBoundsException e) {
			// ArrayIndexOutOfBoundsException : unchecked exception
				// 배열의 첨자가 벗어난 경우 발생하는 예외
			System.out.println("입력을 초과 했습니다...");
		} finally {
			System.out.println("예외 발생 여부와 상관 없이 실행 합니다.");
			sc.close();
		}
		
		System.out.println("\n입력 문자열...");
		for(String str : ss) {
			System.out.println(str);
		}

	}
}

package ex0727;

import java.util.Scanner;

public class Ex107_finally {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a, b, c;

		try {
			System.out.print("두정수 ? ");
			a = sc.nextInt();
			b = sc.nextInt();

			c = a / b;
			System.out.println(a + "/" + b + "=" + c);
		} finally {
			System.out.println("예외발생 여부와 상관 없이 실행 됩니다.");
			sc.close();
		}

		// 예외가 발생하면 실행하지 않는다.
		System.out.println("end...");

	}
}

package ex0727;

public class Ex108_finally {
	public static void main(String[] args) {
		// divide(10, 5);
		// divide(10, 0);
		divide(10, -5);

	}

	public static void divide(int a, int b) {
		try {
			if (b < 0) {
				System.out.println("음수를 입력 했습니다.");
				return;
			}

			int c = a / b;
			System.out.println(a + "/" + b + "=" + c);

		} catch (ArithmeticException e) {
			System.out.println("0으로 나눌 수 없습니다.");
		} finally {
			// System.exit(0);// 프로그램 강제 종료를 만났을 때만 실행하지 않는다.
			System.out.println("finally 블럭은 return을 만나도 실행된다.");
		}

		System.out.println("end...");
	}
}

package ex0727;

import java.util.Scanner;

public class Ex101_exception {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a, b, c;
		
		System.out.print("두정수 ? ");
		a = sc.nextInt();
		b = sc.nextInt();
		
		c = a / b;
		System.out.println(a+"/"+b+"="+c);
		
		// b가 0인 경우 프로그램은 강제로 종료되어 아래 내용이 실행되지 않는다.
		System.out.println("end...");
		
		sc.close();
	}
}

package ex0727;

import java.util.Scanner;
/*
 - 예외가 발생하지 않는 경우
   1) 블럭 모두 실행
   3) 블럭 실행 - 종료
 
 - 예외가 발생한 경우(1번 블럭)
   1) 블럭 실행 중 예외 발생(비정상적인 상황) - 1)블럭 실행을 중지하고
   2) 블럭 실행(예외가 발생한 경우만 실행)
   3) 블럭 실행 - 종료
 */
public class Ex102_exception {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a, b, c;
		
		try {
			// 1) 예외가 발생할 가능성이 있는 코드를 기술
			System.out.print("두수 ? ");
			a = sc.nextInt();
			b = sc.nextInt();
			c = a / b;
			System.out.println(a + "/" + b + "=" + c);
			
		} catch (Exception e) {
			// Exception : 모든 예외를 catch 할 수 있지만 예외 상황별로 예외를 분리할 수 없다.
			// 2) 예외가 발생할 때 실행할 코드 작성
			System.out.println("에러가 발생했습니다.");
		}

		// 3)
		System.out.println("end...");
		sc.close();
	}

}

package ex0727;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Ex103_exception {
	public static void main(String[] args) {
		// 버퍼를 이용하여 문자(열)을 입력 받음. 입력 속도 향상.
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String s;
		int a, b, c;
		
		try {
			System.out.print("첫번째 수 ?");
			s = br.readLine();
				// readLine()은 checked exception(IOException)이 발생하므로 
				// 반드시 예외처리 해야함.
			
			a = Integer.parseInt(s); // 문자열을 숫자로 바꿈
				// NumberFormatException 이라는 unchecked exception 발생
			
			System.out.print("두번째 수 ? ");
			b = Integer.parseInt(br.readLine());
			
			c = a / b;
				// 0으로 나누면 ArithmeticException 이라는 unchecked exception 발생
			
			System.out.println(a + "/" + b + "=" + c);
			
		} catch (IOException e) {
			// IOException : 입출력에 문제가 발생할 때 발생하는 예외(checked exception)
			// checked exception은 메소드를 정의할 때 throws 한 예외
			// checked exception은 예외처리를 하지 않으면 컴파일 에러가 발생하는 예외
			e.printStackTrace(); // 에러 메시지를 표준 출력 장치에 출력
		}
		
		// 0으로 나누거나 문자열이 입력되면 에외가 발생되어 비정상 종료되며, 아래 메시지는 출력되지 않는다.
		System.out.println("end...");
	}
}

package ex0727;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Ex104_exception {
	public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int a, b, c;
		
		try {
			System.out.print("첫번째 수 ? ");
			a = Integer.parseInt(br.readLine());
			
			System.out.print("두번째 수 ? ");
			b = Integer.parseInt(br.readLine());
			
			c = a / b;
			
			System.out.println(a + "/" + b + "=" + c);
		
		// 예외 발생별로 예외를 catch
		} catch (IOException e) { // checked 예외 (반드시 catch해야함)
			e.printStackTrace();
		} catch (NumberFormatException e) {
			// unchecked exception
			// 문자열을 숫자로 변경하지 못하는 경우 등에 발생
			// 반드시 catch 할 필요는 없지만 catch하지 않는 경우 예외가 발생하면 프로그램은 비정상 종료
			
			// System.out.println("숫자만 입력 가능합니다...");
			// System.out.println(e.getMessage()); // 간단한 메시지 출력
			// System.out.println(e.toString()); // 예외 종료 및 간단한 메시지
			e.printStackTrace(); // 자세한 에러 메시지 및 에러 발생 줄 표시 ★ 개발자가 사용해야 할 메소드
			
		} catch (ArithmeticException e) {
			// unchecked exception
			// 숫자를 0으로 나누는 등 연산이 불가능하는 경우 발생
			System.out.println("0으로 나눌수는 없습니다.");
			
		} catch (Exception e) {
			// Exception : 모든 예외를 catch 할 수 있다.
			// 여러 예외를 catch하는 경우에는 다른 예외 클래스의 상위 클래스이므로
			// 		가장 마지막에 위치해야 한다.
			e.printStackTrace();
		}
		
		System.out.println("end...");

	}
}​

package ex0727;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Ex105_exception {
	public static void main(String[] args) {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int a, b, c;
		
		try {
			System.out.print("첫번째 수 ? ");
			a = Integer.parseInt(br.readLine());
			
			System.out.print("두번째 수 ? ");
			b = Integer.parseInt(br.readLine());
			
			c = a / b;
			
			System.out.println(a + "/" + b + "=" + c);
		
		} catch (Exception e) {
			// Exception : 모든 예외를 catch 할 수 있다.
			// 예외별로 예외를 분리할 수 없다.
			// 정모르겠으면 이렇게라도 예외처리를 해라.
			e.printStackTrace();
		} 
		
		System.out.println("end...");

	}
}

예외처리

checked exception 과 uncheck exception로 나뉨.

checked exception은 오류를 잡지 않으면 컴파일 오류가 나타난다.

uncheck exception은 잡지 않아도 되지만 런타임 오류가 생길 수 있다. 생길 수 있는 오류들의 경우를 생각해서 catch로 잡고 (세세한 오류먼저) 마지막에 모든 오류를 잡는 exception을 넣어주는 것이 좋은 코드이다. 

package ex0727;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Ex109_exception {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int a, b, c;

		try {
			System.out.print("두 수 ? ");
			a = sc.nextInt();
			b = sc.nextInt();
			c = a / b;
			System.out.println(a + "/" + b + "=" + c);
		} catch (InputMismatchException e) {
			// InputMismatchException : Scanner의 nextInt() 등에서 숫자가 아닌 문자열을 입력하면
				// 발생하는 unchecked exception
			System.out.println("숫자만 입력 가능합니다.");
		} catch (ArithmeticException e) {
			System.out.println("연산이 불가능 합니다.");
		} finally {
			// finally 블럭에서 일반적으로 사용한 resource를 close한다.
			sc.close();
		}

		System.out.println("end...");
	}
}

 

'쌍용강북교육센터 > 7월' 카테고리의 다른 글

0727_Ex110_tryResource  (0) 2021.07.27
0727_Ex106~Ex108_finally  (0) 2021.07.27
0726_Ex07_interface : 인터페이스  (0) 2021.07.26
0726_Ex06_interface : 인터페이스  (0) 2021.07.26
0726_Ex05_interface : 인터페이스  (0) 2021.07.26
package ex0726;

public class Ex07_interface {
	public static void main(String[] args) {
		int s = Demo7.sum(10);
		System.out.println(s);
		
		Demo7 dm = new DemoImpl7();
		int x = dm.max(5, 10);
		dm.write(x);
	}
}
// interface는 순수하게 선언하는 것만 하는 게 더 좋을 것 같다 = 쌤
interface Demo7 {
	public void write(int n);
	
	// JDK 8부터 가능. 인터페이스를 이용하여 바로 접근 가능
	public static int sum(int n) {
		int s = 0;
		for( int i=1; i<=n; i++) {
			s+=i;
		}
		return s;
	}

	// JDK 8부터 가능. 
	// default 키워드를 이용하여 메소드 구현 가능
	// 구현 클래스에서 재정의 가능
	public default int max(int m, int n) {
		return m > n ? m : n;
	}
}

class DemoImpl7 implements Demo7 {
	@Override
	public void write(int n) {
		System.out.println("결과 : " + n);
		
	}
}

원래 interface는 추상클래스의 일종이므로 선언된 것을 다른 클래스에서 재정의를 하고 그 클래스를 생성해서 재정의된 메소드를 부르는 식 or 다른 클래스에 있는 static 메소드는 객체 생성없이 접근 가능임 여기서는 인터페이스에 구현된 static 클래스도 바로 접근이 가능함을 보았다. 또 default키워드를 이용해 메소드 구현이 가능하다. (이 전에는 틀을 만들어주었기 때문에 굳이 메소드를 구현하지 않고 다른 클래스에서 재정의해서 사용했었다) 물론 구현클래스에서 재정의도 가능하다. 

원래 interface클래스에 선언된 메소드를 구현 클래스에서 재정의를 하지 않으면 안됐는데 default로는 interface에 있는 메소드를 재정의하지 않고도 접근할 수 있다.  

 

package ex0726;

public class Ex06_interface {
	public static void main(String[] args) {
		Store st = new Store();
		
		// Orange ob = new Orange();
		Fruit ob = new Orange();
		st.sell(ob);
		st.sell(new Apple());
		
		
	}
}
interface Fruit {
	public int getPrice();
	public String getName();
}

class Apple implements Fruit {
	@Override
	public int getPrice() {
		return 1000;
	}

	@Override
	public String getName() {
		return "사과";
	}
}

class Orange implements Fruit {
	@Override
	public int getPrice() {
		return 800;
	}

	@Override
	public String getName() {
		return "오렌지";
	}
}

class Store {
	public void sell(Fruit ft) {
		System.out.println(ft.getName() + " - > " + ft.getPrice());
	}
}

인터페이스는 추상 클래스 종류이다.

클래스를 위한 템플릿이다.

 

과일로 친다면

과일의 이름과 가격을 인터페이스의 메소드로 선언해놓음.

Apple 클래스에서 Fruit를 구현했을 때 이름과 가격을 재정의 해야만 컴파일 오류가 발생하지않는다. (이름과 가격이 틀이기 때문에 그 틀에 맞춰서 Apple을 구현한다.) 나중에 Store클래스의 sell메소드에서 Fruit의 틀에 맞춰 생성된 과일들의 객체를 받아 과일의 이름과 가격을 출력해준다.

package ex0726;

public class Ex05_interface {
	public static void main(String[] args) {
		DemoImpl5 di = new DemoImpl5();
		di.print();
	}
}
interface Ademo5 {
	public void print();
}

interface Bdemo5 {
	public void disp();
}

// 인터페이스는 다른 인터페이스를 상속 받을 수 있다.
// 인터페이스는 클래스와 다르게 2개 이상의 인터페이스를 상속 받을 수 있다.
interface Cdemo5 extends Ademo5, Bdemo5 {
	public void sub();
}

class DemoImpl5 implements Cdemo5 {

	@Override
	public void print() {
		System.out.println("print ...");
	}

	@Override
	public void disp() {
		System.out.println("disp ...");
	}

	@Override
	public void sub() {
		System.out.println("sub ...");
	}
	
}

DemoInpl5에서 print() disp() sub()를 재정의 하지 않으면 컴오류! 인터페이스에서 선언된 메소드 들은 구현된 클래스에서 실행하기 위해서 재정의되어야 한다.

'쌍용강북교육센터 > 7월' 카테고리의 다른 글

0726_Ex07_interface : 인터페이스  (0) 2021.07.26
0726_Ex06_interface : 인터페이스  (0) 2021.07.26
0726_Ex04_interface : 인터페이스  (0) 2021.07.26
0726_Ex03_interface 인터페이스  (0) 2021.07.26
0726_Ex02_interface  (0) 2021.07.26
package ex0726;

public class Ex04_interface {
	public static void main(String[] args) {
		Demo4 ob = new Test4(); // up casting
		ob.print();
		ob.disp();
	
	}
}
interface Demo4 {
	public void print();
	public void disp();
}

// 추상 클래스는 인터페이스의 모든 메소드를 구현하지 않아도 된다.
abstract class DemoImple4 implements Demo4 {
	@Override
	public void disp() {
		System.out.println("disp 메소드 ...");
	}
}

class Test4 extends DemoImple4 {
	@Override
	public void print() {
		System.out.println("print 메소드 ...");
	}
}

'쌍용강북교육센터 > 7월' 카테고리의 다른 글

0726_Ex06_interface : 인터페이스  (0) 2021.07.26
0726_Ex05_interface : 인터페이스  (0) 2021.07.26
0726_Ex03_interface 인터페이스  (0) 2021.07.26
0726_Ex02_interface  (0) 2021.07.26
0726_Ex01_abstract : 추상 클래스  (0) 2021.07.26
package ex0726;

public class Ex03_interface {
	public static void main(String[] args) {
		DemoImpl3 di1 = new DemoImpl3();
		di1.print();
		di1.disp();
		di1.sub();
		
		Ademo3 di2 = new DemoImpl3(); // up casting
		Bdemo3 di3 = new DemoImpl3(); // up casting
		
		// di2.print(); // 컴파일 오류. Ademo3 인터페이스에는 print() 메소드가 선언되어 있지 않음.
		((Bdemo3)di2).print();
			// 클래스에 Ademo3과 Bdemo3 인터페이스가 구현되어 있으므로 가능.
			// 만약 Bdemo3 인터페이스가 구현되어 있지 않으면 런타임 오류 발생.
		
		((DemoImpl3)di3).sub(); // 다운 캐스팅
	}
}
interface Ademo3 {
	public void disp();
}

interface Bdemo3 {
	public void print();
}

// 클래스는 2개 이상의 인터페이스를 구현할 수 있다.(다중 상속이 되지 않는 부분을 보충)
class DemoImpl3 implements Ademo3, Bdemo3 { // 이게 중요한 부분!!!

	@Override
	public void print() {
		System.out.println("Bdemo3 인터페이스 메소드 ...");
	}

	@Override
	public void disp() {
		System.out.println("Ademo3 인터페이스 메소드 ...");
	}
	
	public void sub() {
		System.out.println("클래스에 정의된 메소드 ...");
	}
	
}

인터페이스를 여러개 만들어 두고 클래스에 그 여러 개를 상속받을 수 있다! 그렇기에 형제들끼리는 서로 캐스팅될 수 없는데 여기에서는 구현된 인터페이스끼리는 캐스팅이 가능.

+ Recent posts