본문 바로가기
JAVA SE/Code

CODE [20.07.29/Day_15] Java SE / Stack과 Queue, Exception(Exception(try, catch, finally | throws, throw)

by 파프리카_ 2020. 7. 29.
728x90
반응형

[ Stack ]

 

empty() 메서드를 이용하여, 모든 요소 추출

/TestStack.java

import java.util.Stack;

public class TestStack {
	public static void main(String[] args) {
		Stack<String> stack = new Stack<String>();

		// 축적 메서드 : push(value)
		stack.push("a");
		stack.push("b");
		stack.push("c");
		stack.push("d");
		stack.push("e");
		System.out.println(stack); // [a, b, c, d, e]
	
		// 요소 유무 확인 메서드 :empty()
		// 요소 있으면 False, 비어있으면 True
		System.out.println(stack.empty()); // false

		while (stack.empty() == false) {
			System.out.println(stack.pop());
			/*
			 * 출력값: 
			 * e 
			 * d 
			 * c 
			 * b 
			 * a
			 */
		}
	}
}

 


[ Queue ]

isEmpty() 메서드를 이용하여, 모든 요소 추출

/TestQueue.java

package step1;

import java.util.LinkedList;
import java.util.Queue;

public class TestQueue {
	public static void main(String[] args) {
		Queue<String> queue = new LinkedList<String>();
		
		// 축적 메서드 : add(value)
		queue.add("안녕하세요");
		queue.add("문자 보시면 답장 부탁드립니다");
		queue.add("빨리 답장 주세요!");
		queue.add("기한 만료되어 신청이 취소되었습니다.");

		// 요소 유무 확인 메서드: isEmpty();
		System.out.println(queue.isEmpty()); //false
		
		while (queue.isEmpty() == false) {
			System.out.println(queue.poll());
			/* 출력값:
			 * 안녕하세요 
			 * 문자 보시면 답장 부탁드립니다 
			 * 빨리 답장 주세요! 
			 * 기한 만료되어 신청이 취소되었습니다.
			 */
		}
	}
}

 


[ Exception ]

java.lang.Object

 

package step3;

//Exception class
class InformationException extends Exception {

	// overloading
	public InformationException(String message) {
		super(message);
	}

}
//DAO class
class MemberDAO{
	public void registerInfo(String info) throws InformationException{
		if  (info == null)
			throw new InformationException("null이므로 DB에 insert 불가");
		if (info.equals("")) 
			throw new InformationException("공란이므로 DB에 insert 불가");
		// if문에 안걸리면 수행됨
		System.out.println("<" + info + ">" + " DataBase에 insert 완료");
	}
}


//main class
public class TestThrows3 {
	public static void main(String[] args) {
		/*
		 * String data1 = ""; 
		 * String data2 = null; 
		 * System.out.println(data1.equals("")); // true 
		 * System.out.println(data2 == null); //true
		 */
		
		MemberDAO dao = new MemberDAO();
		
		try
		{
			dao.registerInfo("블레어");
			//<블레어> DataBase에 insert 완료
			
			dao.registerInfo("");
			// if문에 걸려서 throw에 의해 InformationException호출 -> catch로 감
			
			dao.registerInfo(null);
			//앞에 try가 exception에 걸려서 실행이 되지 않음
		}
		
		catch(InformationException e)
		{
			System.out.println(e.getMessage());
			//Exception message 출력 : 공란이므로 DB에 insert 불가
			//Exception message 출력 : null이므로 DB에 insert 불가
		}
		
		
		System.out.println("프로그램 정상 수행");
		
		/* 출력값 : 
		* <블레어> DataBase에 insert 완료
		* 공란이므로 DB에 insert 불가
		* 프로그램 정상 수행
		*/
	}
}

 

 

728x90
반응형