다중 Catch문
- 예외가 발생하면 예외 객체가 전달되는 Catch 블럭으로 이동해서 수행문을 수행
주의
다중 Catch문을 사용할 때 Exception과 하위 예외 클래스를 동시에 명시할 때 하위 예외 클래스를 먼저 명시하고 가장 뒤에 >Exception을 명시해야 동작상의 문제가 발생하지 않는다.
public class ExceptionMain03 {
public static void main(String[] args) {
int var = 50;
try {
//String ---> int 변환 작업
int data = Integer.parseInt(args[0]);
System.out.println(var / data);
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("입력한 데이터가 없습니다.");
}
catch (NumberFormatException e) {
System.out.println("숫자가 아닙니다.");
}
catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다.");
}
catch(Exception e) {
System.out.println("나머지 예외는 여기로...");
}
System.out.println("프로그램 종료");
}
멀티 Catch문
- 하나의 Catch 블럭에서 여러개의 예외 처리할 수 있도록 예상되는 예외클래스를 여러 개 명시하는 방식
public class ExceptionMain04 {
public static void main(String[] args) {
try {
int value1 = Integer.parseInt(args[0]);
int value2 = Integer.parseInt(args[1]);
int result = value1 + value2 ;
System.out.println( value1 + " + " + value2 + " = " + result);
}
catch (ArrayIndexOutOfBoundsException | NumberFormatException e) {
//System.out.println("실행 매개 변수 값이 부족하거나 숫자를 변환할 수 없습니다.");
//System.out.println(e.toString()); ==> 예외 정보를 제공
e.printStackTrace();
}
catch (Exception e) {
System.out.println("알 수 없는 예외 발생");
}
}
}
try ~ catch ~ finally 문
- Finally 영역은 예외가 발생하든 발생하지 않든 무조건 수행하는 부분이다.
package kr.s26.exception;
public class ExceptionMain05 {
public static void main(String[] args) {
System.out.println("=====예외 미발생 경우=====");
try {
System.out.println(1);
System.out.println(2);
}
catch (Exception e) {
System.out.println(3);
}
finally {
System.out.println(4);
}
System.out.println();
System.out.println("=====예외 발생 경우=====");
try {
System.out.println("1");
System.out.println(10/0); // 예외 발생!
System.out.println("2"); // 미실행
}
catch (Exception e) { // 예외 발생 후 바로 넘어옴
System.out.println("3");
}
finally { // 예외 실행, 미실행과 관련 없이 무조건 실행
System.out.println("4");
}
}
}
Throws 예약어
- 메서드에 Throws 예외 클래스를 명시하면 메소드 내에 try~catch 블럭을 생략하고 예외가 발생하면 예외를 임시 보관하고 메소드를 호출하는 곳에 try ~ catch 블럭이 있을 경우 그 곳으로 예외를 양도한다.
import java.io.*;
public class ExceptionMain06 {
public void printData() throws IOException , NumberFormatException{
// 입력받을 준비 Scanner 대신 쓰는 애
BufferedReader br = new BufferedReader ( new InputStreamReader(System.in));
System.out.print("단 입력 > ");
// String -> int 변환
int dan = Integer.parseInt(br.readLine()); // 한 라인에 입력한 데이터를 반환
System.out.println(dan + "단");
System.out.println("---------------------");
for( int i = 1 ; i <= 9; i ++) {
System.out.println(dan + " * " + i + " = " + (dan * i));
}
}
public static void main(String[] args) {
ExceptionMain06 em = new ExceptionMain06();
try {
em.printData();
}
catch(IOException e) {
System.out.println("입력시 오류 발생");
}
catch(NumberFormatException e) {
System.out.println("숫자가 아닙니다.");
}
}
}
public class ExceptionMain07 {
public void methodA(String [] n) throws Exception {
if(n.length > 0) { // 데이터 입력 O
for ( String s : n) {
System.out.println(s);
}
}
else {// 데이터 입력 X
//예외를 인위적으로 발생시킴
throw new Exception("배열에 요소가 없습니다");
}
}
public static void main(String[] args) {
ExceptionMain07 em = new ExceptionMain07();
try {
em.methodA(args);
}
catch (Exception e) {
//예외 문구 출력
//System.out.println(e.toString());
System.out.println(e.getMessage());
}
}
}
import java.util.*;
//사용자 정의 예외 클래스
class NegativeNumberUseException extends Exception {
public NegativeNumberUseException (String str) {
super(str);
}
}
public class ExceptionMain08 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("0 이상만 입력 > ");
try {
int a = input.nextInt() ;
if (a >= 0 ) {
System.out.println("입력한 숫자 : " + a);
}
else {// 음수 입력
//사용자 정의 예외 클래스에 예외 문구를 저장해서 객체에 생성 해서 예외를 발생시킴
throw new NegativeNumberUseException ("음수를 사용할 수 없습니다.");
}
}
catch (NegativeNumberUseException e) {
System.out.println(e.getMessage());
}
catch (Exception e) {
System.out.println("예외 발생");
}
finally {
if(input != null)
input.close();
}
}
}
import java.util.*;
class A {
@Override
public String toString() {
return "A" ;
}
}
class B { }
public class ArrayListMain01 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
//ArrayList에 객체 저장하기
list.add(new A());
list.add(new B());
list.add("홍길동");
list.add(10); // int -> Integer (auto boxing)
// 저장된 요소의 목록
System.out.println(list);
// 요소의 갯순
System.out.println(list.size());
}
}
List 구조의 특징
- 저장된 순서 유지, 중복 저장 허용
package kr.s27.collection;
import java.util.*;
public class ArrayListMain02 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("이동욱"); // String -> Object
list.add("이수혁"); // String -> Object
list.add("유재석"); // String -> Object
list.add("손석구"); // String -> Object
// 저장된 요소의 목록
System.out.println(list);
System.out.println("---------------");
for (int i = 0; i < list.size(); i ++) {
String name = (String) list.get(i) ;
System.out.println(name);
}
}
}
제네릭 표현
- 객체를 생성할 때 객체에 저장할 수 있는 요소의 타입을 지정하는 것
import java.util.*;
public class ArrayListMain03 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("이동욱"); //String -> Object
list.add("이수혁"); //String -> Object
//list.add(1000); // Integer -> Object 객체에 저장할 수 있는 데이터의 타입을 String으로 한정시킴
list.add("손석구"); // String -> Object
// 반복문을 이용한 요소의 출력
for (int i = 0 ; i < list.size() ; i ++) {
String name = (String)list.get(i);
System.out.println(name);
}
System.out.println("---------------------");
//확장 for문을 이용한 요소의 출력
for (String name : list) {
System.out.println(name);
}
}
}
요소의 삭제
- String
- 인덱스 명시하여 삭제 : list . remove ( index 번호) ;
- 데이터를 직접 입력하여 삭제 : list . remove ( " 데이터 내용 " );
- 중복된 데이터가 있으면 동시 삭제는 불가능하며, 앞의 순서부터 삭제가 된다.
- Int
- 인덱스 명시하여 삭제 : list . remove ( index 번호) ;
- 데이터를 직접 입력하여 삭제 : list . remove ( Integer.valueOf( 데이터 값));
- 40을 지우기 위해 40을 입력하면 인덱스 40으로 인식하기 때문에 Integer형이라는 것을 인지시켜줘야 한다.
요소의 변경 list.set( , );
- 바꿀 인덱스 번호, 바꿀 값 [인덱스 1의 값을 30으로 바꾼다]
package kr.s27.collection;
import java.util.*;
public class ArrayListMain04 {
public static void main(String[] args) {
//String 데이터
ArrayList<String> list = new ArrayList<String>();
list.add("손석구"); //String
list.add("김우석"); //String
list.add("이동욱"); //String
list.add("이수혁"); //String
list.add("이동욱");//String
//반복문을 이용한 요소의 출력
for(int i = 0; i <list.size(); i++) {
System.out.println(i+ " : " + list.get(i));
}
System.out.println("--------------");
// 요소의 삭제
//인덱스 명시하여 삭제
list.remove(2);
// 중복된 데이터가 있으면 동시는 삭제는 불가능하며, 앞에서부터 삭제된다
list.remove("이동욱");
for(int i = 0; i <list.size(); i++) {
System.out.println(i+ " : " + list.get(i));
}
System.out.println("--------------");
// int 데이터
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2.add(40);
list2.add(1);
list2.add(2);
list2.add(3);
list2.add(40);
//요소의 출력
for(int i = 0; i <list2.size(); i++) {
System.out.println(i+ " : " + list2.get(i));
}
System.out.println("--------------");
//요소의 삭제
//인덱스 명시하여 삭제
list2.remove(2);
//40을 쓰면 인덱스 40으로 인식하기 때문에 Integer.valueOf() 를 써서 Integer라는 것을 알려줘야한다.
list2.remove(Integer.valueOf(40));
for(int i = 0; i <list2.size(); i++) {
System.out.println(i+ " : " + list2.get(i));
}
System.out.println("--------------");
//요소의 변경
// 바꿀 인덱스 번호, 바꿀 값 [인덱스 1의 값을 30으로 바꾼다]
list2.set(1, 30);
for(int i = 0; i <list2.size(); i++) {
System.out.println(i+ " : " + list2.get(i));
}
}
}
짝수 삭제
- 마지막 인덱스부터 시작해서 조건 체크하면 건너뛰는 데이터가 발생하지 않고 모든 요소의 조건 체크가 가능하다.
마지막 인덱스 번호 : 길이 - 1
import java.util.*;
public class ArrayListMain05 {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(10);
list.add(20);
list.add(15);
list.add(16);
//저장된 요소의 목록
System.out.println(list);
System.out.println("-----------------");
/* 짝수 삭제 잘못된 방법
이 방법으로 진행하게 된다면 삭제 처리를 놓치는 데이터가 생길 수 있다.
그래서 큰 인덱스 숫자부터 삭제를 진행시켜야 빠지지 않고 삭제가 될 수 있다.
for (int i = 0 ; i < list.size(); i++) {
if(list.get(i)%2 == 0) {
list.remove(i);
} if
} for
System.out.println(list);
System.out.println("-----------------");
*/
//짝수 삭제하기
for (int i = list.size() - 1; i >= 0; i--) {
if(list.get(i)%2 == 0) {
list.remove(i);
} //IF
} //FOR
System.out.println(list);
System.out.println("-----------------");
}
}
인덱스 탐색
package kr.s27.collection;
import java.util.*;
import javax.xml.transform.sax.SAXSource;
public class ArrayListMain06 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("딸기"); //0
list.add("샤인머스캣"); //1
list.add("자두"); //2
list.add("딸기"); //3
list.add("체리"); //4
//인덱스 탐색
int index1 = list.indexOf("딸기");
System.out.println("첫 번째 딸기 : " + index1);
// 마지막 인덱스 탐색
int index2 = list.lastIndexOf("딸기");
System.out.println("마지막 딸기 : " + index2);
//없는 데이터는 -1 반환 시킴
int index3 = list.indexOf("망고");
System.out.println("망고의 위치? " + index3);
//샤인머스캣이 포함되어 있으면 true / 없으면 false
boolean f1 = list.contains("샤인머스캣");
System.out.println("샤인머스캣 포함? " + f1);
// 미포함 과일이기 때문에 false 반환
boolean f2 = list.contains("방울토마토");
System.out.println("방울토마토 포함? " + f2);
System.out.println("-------------");
// 요소의 목록 출력
System.out.println(list);
System.out.println("------------");
// 사전에 명시된 순서대로 정렬
Collections.sort(list);
System.out.println(list);
// 역순으로 정렬
Collections.reverse(list);
System.out.println(list);
System.out.println("-----------");
// INT 형
ArrayList <Integer> list2 = new ArrayList<Integer> ();
list2.add(10);
list2.add(100);
list2.add(15);
list2.add(2);
list2.add(40);
System.out.println(list2);
System.out.println("--------------");
//정렬 (오름차순 정렬)
Collections.sort(list2);
System.out.println(list2);
//내림차순 정렬
Collections.reverse(list2);
System.out.println(list2);
}
}
package kr.s27.collection;
import java.util.*;
public class ArrayListMain07_test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
Random ra= new Random ();
while (list.size() < 6) {
// 난수 발생 (1~45)
int num = ra.nextInt(45) + 1;
//중복값 체크
if(!list.contains(num)) {
list.add(num);
} // IF
} // WHILE
// 오름차순 정렬
Collections.sort(list);
// 출력
for(int num : list ) {
System.out.print(num + "\t");
}
}
}
package kr.s27.collection;
import java.util.*;
public class ArrayListMain08 {
public static void main(String[] args) {
// 2차원 배열 형태를 ArrayList로 구현하기
ArrayList<CartItem> list = new ArrayList <CartItem>();
list.add(new CartItem("A1001" , 2 , 2000));
list.add(new CartItem("B1001" , 1 , 7000));
list.add(new CartItem("C1001" , 3 , 2500));
System.out.printf("%s %8s %8s%n" , "상품코드" , "수량", "가격");
System.out.println("-------------------------------------");
for(CartItem item : list) {
System.out.printf("%s %,8d %,8d%n", item.getCode() , item.getNum() , item.getPrice());
}
System.out.println("-------------------------------------");
//요소의 삭제
list.remove(1);
for(CartItem item : list) {
System.out.printf("%s %,8d %,8d%n", item.getCode() , item.getNum() , item.getPrice());
}
}
}
package kr.s27.collection;
public class CartItem {
private String code; // 상품코드
private int num; // 수량
private int price; // 단가
public CartItem () { }
public CartItem(String code, int num, int price) {
this.code = code;
this.num = num;
this.price = price;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
package kr.s27.collection;
import java.util.*;
public class VectorMain {
public static void main(String[] args) {
Vector<Double> v = new Vector<Double>();
//요소의 추가
v.add(100.3);
v.add(3.14);
v.add(1000.); // = 1000.0
// 확장 for 문을 이용한 출력
for ( Double n : v) {
System.out.println(n);
}
System.out.println("--------------------");
//요소 검색
double search = 1000.0; // 검색할 요소
int index = v.indexOf(search);
if ( index != -1) {
System.out.println("검색 요소 " + search + "의 위치 : " + index);
}
else{
System.out.println("검색 요소 " + search + " 해당 없음.");
}
System.out.println("-------------------------");
//요소 삭제
double del = 3.14; // 삭제할 요소
if(v.contains(del)) { // 삭제할 요소가 Vector의 요소인지 검사
v.remove(del);
System.out.println(del + " 삭제가 완료되었습니다!");
}
else {
System.out.println("해당 요소가 없습니다.");
}
}
}