** 예제 MySample1130 (예외처리 속 예외처리) **

package exec;

public class MySample1130 {

	public static void main(String[] args) {
		// 예외처리
		try {
				System.out.println("외부 try");
				
				try {
					System.out.println("내부 try");
					Exception e = new Exception();
					throw e;
				}
				catch(Exception e) {
					System.out.println("내부 try~catch exception : " + e);
					System.out.println("예외 던기지 한번 더");
					throw e;
				}
		}
		catch(Exception e) {
			System.out.println("외부 try~catch exception : " + e);
		}
		
		System.out.println("예외처리 끝");
	}
}

** 예제 MySample1130_2 (사용자 예외처리 = 클래스 예외처리) **

package exec;

import java.util.Scanner;

public class MySample1130_2 {
	static Scanner scn = new Scanner(System.in);
	
	static void ticketing(int age) throws AgeException{ //ticketing 호출하는 쪽에서 예외처리 해야한다.
		if(age < 20) {
			
			//AgeException e = new AgeException("나이 입력 오류");
			//throw e;
			//위 두줄을 한줄로
			throw new AgeException("나이 입력 오류");
		}
	}

	public static void main(String[] args) {
		// 예외처리 - 사용자 예외처리 (=클래스 예외처리)
		/*
		 * 문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료
		 */
		
		
		System.out.print("나이를 입력하세요.>");
		int age =scn.nextInt();
		
		try {
			ticketing(age);
		}
		catch(AgeException e) {
			e.printStackTrace();
		}
		
		System.out.println("main() 메소드 끝.");
		
	}
}


class AgeException extends Exception{	//Exception 상속 받아야함 (안받으면 Object상속받음)
	AgeException(){
		this("나이 입력 오류");
	}
	AgeException(String msg){
		super(msg);
	}
}

 

//문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료

//문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료

package exec;

import java.util.Scanner;

public class MySample1130_2 {
	static Scanner scn = new Scanner(System.in);
	
	static void ticketing(int age) throws AgeException{ //ticketing 호출하는 쪽에서 예외처리 해야한다.
		if(age < 20) {
			
			//AgeException e = new AgeException("나이 입력 오류");
			//throw e;
			//위 두줄을 한줄로
			throw new AgeException("나이 입력 오류");
		}
	}

	public static void main(String[] args) throws InterruptedException {		//Thread.sleep(1000); 사용하기위해 throws 해준다.
		// 예외처리 - 사용자 예외처리 (=클래스 예외처리)
		/*
		 * 문제)20살 미만이 입력될 경우 계속해서 입력을 받고 20살 이상이 입력되면 "티켓발행 성공"이라고 출력하고 프로그램 종료
		 */
		
		while(true) {
			
			System.out.print("나이를 입력하세요.>");
			int age = scn.nextInt();
			
			try {
				ticketing(age);
				System.out.println("티켓 발행 성공");
				break;
			}
			catch(AgeException e) {
				e.printStackTrace();
				//예쁘게 보이기위해 Thread.sleep(1000); 와 throws InterruptedException 사용해줌
				//위 e.printStackTrace(); 대신 아래문자열로 사용 가능
				System.out.println(e.getMessage());	
			}
			
			Thread.sleep(1000);			//1초 대기
			System.out.println();
			
		}
	}
}

class AgeException extends Exception{	//Exception 상속 받아야함 (안받으면 Object상속받음)
	AgeException(){
		this("나이 입력 오류");
	}
	AgeException(String msg){
		super(msg);
	}
}

** 예제 MySample1130_3 (예외처리)**

package exec;
//예외처리가 어디서 일어나는지 알아보기 위해 쓰인다.(흔하게 쓰이진 않음)
public class MySample1130_3 {

	public static void main(String[] args) {
		// 예외처리 (연결된 예외처리)
		
		try {
			install();
		}
		catch(InstallException e) {
			System.out.println("1111111111111111111111111");
			e.printStackTrace();
		}
		catch(Exception e) {
			System.out.println("2222222222222222222222222");
			e.printStackTrace();
		}
		finally {
			System.out.println("*************************");
		}
	}
	
	static void install() throws InstallException{
		try {
			startInstall();
			copyFiles();
		}
		catch(SpaceException e) {
			InstallException ie = new InstallException("설치중 예외발생11");
			//InstallException의 원인 예외를 SpaceException으로 지정
			ie.initCause(e);			//지정된 예외를 예외로 등록
			throw ie;
			
			//
		}
		catch(MemoryException e) {
			InstallException ie = new InstallException("설치중 예외발생22");
			ie.initCause(e);
			throw ie;
		}
		finally {
			deleteTempFiles();
		}
	}
	
	static void startInstall() throws SpaceException, MemoryException{
		
		if(!enoughSpace()) {
			throw new SpaceException("설치 공간이 부족함.");
		}
		
		if(!enoughMemory()) {
			throw new MemoryException("메모리가 부족함");
		}
	}
	
	
	static void copyFiles() {
		System.out.println("설치에 필요한 파일들을 복사.");
	}
	
	static boolean enoughSpace() {
		System.out.println("설치시 필요한 공간이 충분한지 확인.");
		return false;
	}
	
	static boolean enoughMemory() {
		System.out.println("설치시 필요한 메모리 확인");
		return true;
	}
	
	static void deleteTempFiles() {
		System.out.println("설치 후 설치시 사용한 임시파일 삭제.");
	}
	
}


class InstallException extends Exception{
	
	InstallException(String msg){
		super(msg);
	}

 




** Java.lang패키지 **

- 가장 기본이 되는 클래스들을 포함하고 있으며, import문 없이도 사용가능

 

Object클래스 : 모든 클래스의 최고 조상

Object 클래스의 메소드  설명
public Boolean equals(Object obj) 객체 자신과 객체 obj가 같은 객체인 기 (같으면 true)
public Class getClass() 객체 자신의 클래스 정보를 담고 있는 Class 인스턴스를 반환
public int hachCode() 객체 자신의 해시코드를 반화
public String toString() 객체 자신의 정보를 문자열로 반환

 

Object클래스에 equals메소드는 참조변수가 같은 객체를 참조하는 판다.

String 클래스의 epuals메소드는 주소값이 아닌 내용을 비교하도록 오버라이딩 되어있음.

public String toString{
                  reurn getCalss().getName() + "@" + integer.toHexString(hashCode());
                  //실행예) Card@19e0bfd
}

 

 


** 예제 MySample1130_4 **

package exec;

class  Value{
	
	int value;
	
	Value(int value){
		this.value = value;
	}
}

public class MySample1130_4 {

	public static void main(String[] args) {
		//java.lang 패키지
		Value v1 = new Value(20);
		Value v2 = new Value(20);
		
		if(v1.equals(v2)) {
			System.out.println("v1과 v2가 같습니다.");
		}
		else {
			System.out.println("v1과 v2가 다릅니다.");
		}
		
		v1 = v2;
		
		if(v1.equals(v2)) {
			System.out.println("v1과 v2가 같습니다.");
		}
		else {
			System.out.println("v1과 v2가 다릅니다.");
		}
	}
}

** 예제 MySample1130_5 **

package exec;

public class MySample1130_5 {

	public static void main(String[] args) {
		//equals 메소드 오버라이딩
		Person p1 = new Person(102345677722L);
		Person p2 = new Person(102345677722L);
		
		if(p1 == p2) {
			System.out.println("p1과 p2가 같습니다.");
		}
		else {
			System.out.println("p1과 p2가 다릅니다.");
		}
		
		if(p1.equals(p2)) {
			System.out.println("p1과 p2가 같다.*");
		}
		else {
			System.out.println("p1과 p2가 다르다.*");
		}
		
	}
}


class Person{
	
	long id;
	
	Person(long id){
		this.id = id;
	}
	
	@Override
	public boolean equals(Object obj) {	//Object 참조형을 받는다는 의미 - Object클래스 상속받는 모든 객체를 매개변수로 받을 수 있다.
		
		if(obj instanceof Person) {
			
			if(this.id == ((Person)obj).id) 
				return true;
			else
				return false;
			//if절 4줄을 아래 한 줄로 표현 가능
			//return this.id == ((Person)obj).id;
		}
		else
			return false;
	 }
}

** 예제 MySample1130_6 **

package exec;

public class MySample1130_6 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Card c1 = new Card();
		Card c2 = new Card("heart", 10);
		
		System.out.println("c1.toString : " + c1.toString());
		System.out.println("c2.toString : " + c2.toString());
		
		String str = new String("korea");
		String str1 = "korea";
		
		System.out.println("str : " + str);
		System.out.println("str.toString : " + str.toString());
		
		System.out.println("str1 : " + str1);
		System.out.println("str1.toString : " + str1.toString());
		
	}

}

class Card{
	String kind;
	int number;
	
	Card(){
		this("spade", 1);
	}
	
	Card(String kind, int number){
		this.kind = kind;
		this.number = number;
	}
	
	void test() {
		Card c = new Card();
		System.out.println(c.toString());
	}
	
	public String toString() {
		return "kind : " + this.kind + ", number : " + this.number;
	}
}



** String클래스 **

- 문자열을 위한 클래스로 문자열을 저장하고 이를 다루는데 필요한 메서드 제공

메서드 설명 예제 결과
int comareTo(String str) int l = "aaa".compareTo("aaa"); i = 0
String cocat(String str) String s1 = "Hello";
String s2 = s1.concat(" World");
s2 = "Hello World"
boolean equals(Object obj) String s = "Hello";
String s2 = s.equals( "Hello" );
s2 = ture;
int indexOf(int ch) String s = "Hello";
int idx1 = s.indexOf('o');
()에 숫자가 들어가면 문자열에서 숫자에 해당하는 문자반환
()에 문자가 들어가면 그 문자가 있는 위치 번호 반환
Index1 =4
int length() String s = "Hello";
int length = s.length();
lenght = 5
String[] split(String regex) String animals = "dog,cat,bear"
String[] arr = animals.split(",");
arr[0] = "dog"
arr[1] = "cat"
arr[2] = "bear"

 


 

** 예제 MySample1130_6 **

package exec;

import java.util.StringJoiner;

public class MySample1130_7 {

	public static void main(String[] args) {
		
		String str1 = "abc";	//문자열 리터럴 "abc"의 주소가 str1에 저장
		String str2 = "abc";	//문자열 리터럴 "abc"의 주소가 str2에 저장 
								//(결과는 str1과 str2는 문자열 "abc"를 같이 바라봄)
		
		System.out.println("String str1 = \"abc\";");
		System.out.println("String str2 = \"abc\";");
		
		System.out.println(str1);	//.toString()메소드 생략되어있음
		System.out.println(str2);
		System.out.println("str1 == str2 : " + (str1 == str2)); 		//String객체는 == 연산자 할 때 객체가 가지고 있는 값을 비교함.
		System.out.println("str1.equals(str2) : " + str1.equals(str2)); //String타입은 .equals로 비교하는 것이 좋음
		
		System.out.println();
		
		String str3 = new String("\"abc\"");		//새로운 String인스턴스 생성
		String str4 = new String("\"abc\"");		//새로운 String인스턴스 생성
		
		System.out.println(str3);
		System.out.println(str4);
		System.out.println("str3 == str4 : " + (str3 == str4));
		System.out.println("str3.equals(str4) : " + str3.equals(str4));
		
		System.out.println();
		/*
		 * 확장형 for문
		 * String[] arr = {"a", "b", "c"};
		 * for(String s : arr)
		 */
		
		String animals = "dog,cat,bear";
		String[] arr = animals.split(",");
		
		for(String s : arr) {
			System.out.print(s + " ");
		}
		
		System.out.println();
		
		System.out.println(String.join("-", arr));			//문자열과 문자열 사이에 "-"로 구분
		StringJoiner sj = new StringJoiner("/","[","]");	
		//문자열을 add할때 - 문자열과 문자열사이 들어갈것(-), 문자열 시작에 들어갈 것([), 문자열 끝에 들어갈 것(])
		
		for(String s : arr){
			sj.add(s);
		}
		
		System.out.println(sj.toString());
	}
}

 

* 결과

String str1 = "abc";
String str2 = "abc";
abc
abc
str1 == str2 : true
str1.equals(str2) : true

"abc"
"abc"
str3 == str4 : false


** 예제 MySample1130_7 **

package exec;

import java.util.StringJoiner;

public class MySample1130_7 {

	public static void main(String[] args) {
		
		String str1 = "abc";	//문자열 리터럴 "abc"의 주소가 str1에 저장
		String str2 = "abc";	//문자열 리터럴 "abc"의 주소가 str2에 저장 
								//(결과는 str1과 str2는 문자열 "abc"를 같이 바라봄)
		
		System.out.println("String str1 = \"abc\";");
		System.out.println("String str2 = \"abc\";");
		
		System.out.println(str1);	//.toString()메소드 생략되어있음
		System.out.println(str2);
		System.out.println("str1 == str2 : " + (str1 == str2)); 		//String객체는 == 연산자 할 때 객체가 가지고 있는 값을 비교함.
		System.out.println("str1.equals(str2) : " + str1.equals(str2)); //String타입은 .equals로 비교하는 것이 좋음
		
		System.out.println();
		
		String str3 = new String("\"abc\"");		//새로운 String인스턴스 생성
		String str4 = new String("\"abc\"");		//새로운 String인스턴스 생성
		
		System.out.println(str3);
		System.out.println(str4);
		System.out.println("str3 == str4 : " + (str3 == str4));
		System.out.println("str3.equals(str4) : " + str3.equals(str4));
		
		System.out.println();
		/*
		 * 확장형 for문
		 * String[] arr = {"a", "b", "c"};
		 * for(String s : arr)
		 */
		
		String animals = "dog,cat,bear";
		String[] arr = animals.split(",");
		
		for(String s : arr) {
			System.out.print(s + " ");
		}
		
		System.out.println();
		
		System.out.println(String.join("-", arr));			//문자열과 문자열 사이에 "-"로 구분
		StringJoiner sj = new StringJoiner("/","[","]");	
		//문자열을 add할때 - 문자열과 문자열사이 들어갈것(-), 문자열 시작에 들어갈 것([), 문자열 끝에 들어갈 것(])
		
		for(String s : arr){
			sj.add(s);
		}
		
		System.out.println(sj.toString());

	}
}



** 날짜와 시간 **

Calendar 클래스 : 추상 클래스이므로 객체를 직접생성할 수 없고, 메서드를 통해서 완전히 구현된 인스턴스를 얻어야 한다.

 

* Calendar클래스의 주요 상수(static final int) - 아래 표에는 final이 생략되어 있다.

cf) 상수 변수는 모두 대문자를 사용하고, 단어와 단어 사이에는 _(언더바)를 넣어준다.

상수 사용방법 설명
static int YEAR Calendar.YEAR 현재 년도를 가져온다
static intMONTH Calendar.MONTH 현재 월을 가져온다.(1월은 0)
static intDATE Calendar.DATE 현재 월의 날짜를 가져온다.
static intWEEK_OF_YEAR Calendar.WEEK_OF_YEAR 현재 년도의 몇째 주
static intWEEK_OF_MONTH Calendar.WEEK_OF_MONTH 현재 월의 몇째 주
static intDAY_OF_YEAR Calendar.DAY_OF_ YEAR 현재 년도의 날짜
static intDAY_OF_MONTH Calendar.DAY_OF_ MONTH 현재 월의 날짜(DATE와 동일)
static intDAY_OF_WEEK Calendar.DAY_OF_ WEEK 현재 요일(일요일1, 토요일7)
static intHOUR Calendar.HOUR 현재시간 (12시간제)
static intHOUR_OF_DAY Calendar.HOUR_OF_DAY 현재시간 (24시간제)
static intMINUTE Calendar. MINUTE 현재 분
static intSECOND Calendar. SECOND 현재 초

 

cf) 추상클래스의 추상메소드를 쓰는 이유 -> 자식클래스가 반드시 그 메소드를 정의해야함을 부여

     인터페이스 

 

* Calendar클래스 메소드

   
   
   
   
   
   
   
   
   
   
   
   

 

Calendar cal = new Calendar();          //에러. 추장클래스는 인스턴스 생성불가

Calendar cal = Calendar.getInstance();   //이렇게 객체생성 해야함

 


** 예제 MySample1130_8 (캘린더) **

package exec;

import java.util.Calendar;

public class MySample1130_8 {

	public static void main(String[] args) {
		// 캘린더 클래스
		
		Calendar today = Calendar.getInstance();
		
		System.out.println("년도 : " + today.get(Calendar.YEAR));
		System.out.println("월, 1월(0) : " + today.get(Calendar.MONTH));
		System.out.println("올해의 몇째 주 : " + today.get(Calendar.WEEK_OF_YEAR));
		System.out.println("이번달의 몇째 주 : " + today.get(Calendar.WEEK_OF_MONTH));
		System.out.println("이달의 며칠 : " + today.get(Calendar.DATE));
		System.out.println("올해의 며칠 : " + today.get(Calendar.DAY_OF_YEAR));
		System.out.println("요일1(일요일) : " + today.get(Calendar.DAY_OF_WEEK));
		System.out.println("이달의 몇째 요일 : " + today.get(Calendar.DAY_OF_WEEK_IN_MONTH));
		System.out.println("오전/오후(0:오전, 1:오후) : " + today.get(Calendar.AM_PM));
		System.out.println("시간(0~11) : " + today.get(Calendar.HOUR));			//12시기준
		System.out.println("시간(0~23) : " + today.get(Calendar.HOUR_OF_DAY));	//24시기준
		System.out.println("분(0~59) : " + today.get(Calendar.MINUTE));
		System.out.println("초(0~59) : " + today.get(Calendar.SECOND));
		System.out.println("이달의 마지막날 : " + today.getActualMaximum(Calendar.DATE));
		
		final String[] DAY_OF_WEEK = {"","일", "월", "화", "수", "목", "금", "토"};
		
		Calendar date1 = Calendar.getInstance();
		Calendar date2 = Calendar.getInstance();
		
		date1.set(2001, 3, 8);
		
		System.out.println("date2 : " + toString2(date2) + DAY_OF_WEEK[date2.get(Calendar.DAY_OF_WEEK)] + "요일입니다.");
		System.out.println("date1 : " + toString2(date1) + DAY_OF_WEEK[date1.get(Calendar.DAY_OF_WEEK)] + "요일입니다.");
		
		
		
		System.out.println();
		
		
		
		System.out.println("=== 1일 후 ===");
		date2.add(Calendar.DATE, 1);
		System.out.println(toString2(date2));
		
		System.out.println("=== 5달 전 ===");
		date2.add(Calendar.MONTH, -5);
		System.out.println(toString2(date2));
		
		System.out.println("=== 31일 후 ===(roll)");
		date2.roll(Calendar.DATE, 20);				//roll -> 일만 바꿔준다.(월은 변경되지 않음)
		System.out.println(toString2(date2));
		
		System.out.println("=== 31일 후 ===(add)");
		date2.add(Calendar.DATE, 20);				//add -> 월과 일을 같이 바꿔준다.
		System.out.println(toString2(date2));
		
	}
	
	public static String toString2(Calendar date) {
		return date.get(Calendar.YEAR) + "년 " + (date.get(Calendar.MONTH)+1) + "월 " + date.get(Calendar.DATE)+ "일 ";
	}
	
}

** 예제 MySample1130_9 (캘린더) **

// 월과 년을 입력받았을 때 날짜를 알려주는 프로그램

package exec;

import java.util.Calendar;

public class MySample1130_9 {

	public static void main(String[] args) {
		// 월과 년을 입력받았을 때 날짜를 알려주는 프로그램
		
		System.out.println("args.length : " + args.length);
		
		if(args.length != 2) {
			System.out.println("args 오류 ... 년과 월을 입력하세요.>");
			return;		//밑에 있는거 실행하지 않고 나를 호출한 곳으로 돌아감 (여기서는 JVM이라서 프로그램종료)
		}
		
		System.out.println("성공 ...");
		
		
		//* args배열에 값입 력하는 법 
		//Project Explorer의 현재 클래스 우클릭 -> run as -> run configurations... -> arguments -> program arguments에 스페이스 기준으로 입력
		
		int year = Integer.parseInt(args[0]);
		int month = Integer.parseInt(args[1]);
		
		Calendar sDay = Calendar.getInstance();		//시작일
		Calendar eDay = Calendar.getInstance();		//끝일
		
		sDay.set(year, month-1, 1);
		//해당월의 마지막날 - 입력월의 마지막날 getActualMaximun 이용
		eDay.set(year, month-1, sDay.getActualMaximum(Calendar.DATE));
		//1일이 속한 주의 일요일로 날짜 선정
		sDay.add(Calendar.DATE, -sDay.get(Calendar.DAY_OF_WEEK) + 1);
		//말일이 속한 주의 토요일 날짜 선정
		eDay.add(Calendar.DATE, 7 - eDay.get(Calendar.DAY_OF_WEEK));
		
		System.out.println(" " + year + "년 " + month + "월");
		System.out.println(" 일  월  화  수  목  금  토");
		
		//시작일부터 마지막일까지 (sDay <= eDay) 1일씩 증가 시키면서
		//일(Calendar.DATE)출력
		int day;
		for(int n = 1 ; sDay.before(eDay)||sDay.equals(eDay) ; sDay.add(Calendar.DATE, 1)) {
			day = sDay.get(Calendar.DATE);
			System.out.print((day < 10) ? ("  " + day) : (" " + day));
			
			if(n++ % 7 == 0) System.out.println();
		}
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

+ Recent posts