JAVA

JAVA 기초 - Exception, Calendar, Class

명주_^ 2022. 6. 8. 17:12

예외(Exception) 

not Error! 프로그램이 멈추지 않는다.

  • NumberFormatException : number 입력인데 A, B, C 등의 str 입력된 경우
  • ClassNotFoundException : class가 없는 경우
  • FileNotFoundException : file이 없는 경우
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • Exception 으로 모두 포함 가능

형식 : 

try {
	// 예외가 발생될 가능성이 있는 코드
} catch (Exception e) { // 예외 클래스 1
	// 메세지 출력
} catch (ExceptionInInitializerError e) { // 예외 클래스 2
	// 메세지 출력
} catch (Error e) { // 예외 클래스 3
	// 메세지 출력
} finally {
	// 무조건 실행
	// rollback
}
static void method() throws Exception{
	// 메소드에서의 예외처리
}

 

  • finally는 무조건 실행되는 코드
  • exception 메세지 출력 방법
e.printStackTrace();
System.out.println(e.getMessage());

 

Calendar

Calendar calendar = new GregorianCalendar();
Calendar cal = Calendar.getInstance();

 

오늘 날짜

int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1; // 0 ~ 11
int day = cal.get(Calendar.DATE);

System.out.println(year + "/" + month + "/" + day);
  • getter/setter 사용 가능
  • set 이용하여 날짜 설정 가능

AM/PM

String ampm = cal.get(Calendar.AM_PM) == 0 ? "오전" : "오후";
System.out.println(ampm);

 

요일

int weekday = cal.get(Calendar.DAY_OF_WEEK); // 1(일) ~ 7(토)

 

마지막 날짜

int lastday = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(lastday);

** 간단한 달력 출력 **

System.out.print("일\t");
System.out.print("월\t");
System.out.print("화\t");
System.out.print("수\t");
System.out.print("목\t");
System.out.print("금\t");
System.out.println("토\t");
String blank = "";
cal.set(Calendar.DATE, 1);
int firstweekday = cal.get(Calendar.DAY_OF_WEEK);
int count = 0;
for (int i = 0; i < firstweekday - 1; i++) {
	blank += "\t";
	count++;
}
for (int i = 1; i <= lastday; i++) {
	if (i == 1) {
		System.out.print(blank);
	}
	if (count % 7 == 0) {
		System.out.println();
	}
	System.out.print(i + "\t");
	count++;
}

결과

 

Class

  • 절차지향 : 순서 중시, 속도가 빠름
  • 객체지향(OOP) : Object Oriented Programming, 분산처리가 가능.

접근지정자

  • public
  • private
  • protected

* 자바의 default 접근 지정자는 variable은 private, method는 public

* 객체 지향 특징 : 캡슐화(은닉성), 상속, 다형성