23일차 시작....

조동현·2022년 8월 2일
0

[교육] Java

목록 보기
8/12
post-thumbnail

📌 Iterator (반복자)

  • iterator
    - 반복자(iterator) 객체를 생성
    - 저장된 item을 순서대로 배치한 것
    - Cursor가 위에서부터 순차적으로 item을 지정함
    - Cursor는 시작할 때, 첫번째 데이터보다 위에 있다.

  • 사용 메소드
    - (Array or Set).iterator() : (Array or Set)에 iterator를 지정한다.
    - iterator.hasNext() : 반복자를 적용한 iterator의 다음 요소가 존재하는지 여부를 반환
    - iterator.next() : 반복자를 적용한 iterator의 다음 요소를 가져옴

  • 형식
Iterator<String> iter = names.iterator();

while(iter.hasNext()) {
	String item = iter.next();
	System.out.println(item);
}


📌 Random 객체

  • Random
    - 범위 내의 특정 값을 랜덤하게 추출하기 위한 객체

  • 형식
int num = ran.nextInt();

int num2 = ran.nextInt(0, 10);


📌 예외 처리

  • try catch
    - Exception이 발생하는 구간에서 예외를 처리하기 위한 문법
    - try : 예외가 발생할 수 있는 구간을 포함
    - catch : 예외 발생 시, 예외 클래스를 정의하고 내부적으로 처리하는 것을 포함
    - finally : 예외 처리와 관계 없이 실행하는 것
    - throw : 특정 상황에 대해서 예외 처리를 하도록 한다.

  • 사용 메소드
    - e.getMessage() : 예외 메시지 반환
    - e.printStackTrace() : 예외 발생 스택 반환

  • 예외 클래스
    - ArithmeticException : 분모가 0일 때, 나누기 연산 시 호출하는 예외 클래스
    - NumberFormatException : casting 할 때, 숫자형 문자열이 아닌 기본 문자열일 때 호출하는 예외 클래스
    - Exception : 전체 예외에 대해 Exception 발생 시 호출하는 예외 클래스

  • 형식
Scanner sc = new Scanner(System.in);
System.out.print("숫자 입력 : ");

String inputNum = sc.nextLine();

try {
	// 예외 발생 구간
	double num = Double.parseDouble(inputNum);
	if(num==5.0) {
		throw new Exception("예외 처리");
	}
	double result = num+100;
	System.out.println(inputNum+" + 100 = "+result);
} catch(NumberFormatException e) {
	// 정수 형태 예외 발생 시 실행하는 구간
	System.out.println("문자열 입력됨");
	System.out.println(e);
	System.out.println(e.getMessage());
	e.printStackTrace();
}


📌 Thread 클래스

  • Thread
    - 쓰레드 동작을 지원하는 클래스
    주의 사항) 반드시 try catch문 안에서 수행해야 한다.
    - 예외 처리 : InterruptedException
    - 이유 : RuntimeException가 부모 클래스에 없는 예외 클래스들은 반드시 try catch문을 사용해야 한다.

  • 사용 메소드
    - sleep() : 몇 초간 쓰레드 동작으로 지연시킨다.

  • 형식
System.out.println("a1");

try {
	Thread.sleep(5000);
} catch (InterruptedException e) {
	e.printStackTrace();
}

System.out.println("a2");


📌 File 클래스

  • File
    - 파일 탐색기

  • 생성자
    - new File("파일 경로") : 파일 경로에 있는 파일을 지정한다.

  • 사용 메소드
    - createNewFile() : 파일 경로에 지정한 파일명으로 새로운 파일을 생성

  • 형식
public static void main(String[] args) {
	File f = new File("C:/acorn202206/test/a.txt");
	try {
		f.createNewFile();
	} catch (IOException e) {
		e.printStackTrace();
	}
}


profile
데이터 사이언티스트를 목표로 하는 개발자

0개의 댓글