본문 바로가기
JAVA

자바 5주차

by Zㅣ존수빈zz 2022. 12. 9.

1. Exception

- Exception은 작성시 예측가능한 오류와 발생할수도, 발생하지 않을 수도 있는 오류에 대해서 표시한다

- java가 지원하는 클래스가 실행될 때 발생하는 오류에 대해서는 RuntimeException으로 표시

  • 존재하지 않는 파일: FileNotFoundException
  • 0으로 나누면: ArithmeticException
  • 배열에서 구할 수 없는 값: ArrayIndexOutOfBoundsException

- 예외처리의 2가지 방법

  • try ~ catch 사용
         try {
              시도할 코드
         } catch ( 예외처리할 특정오류범위(ex) Exception: 모든 예외대상에 대한 예외처리) ) {
              오류가 발생했을 시 시도할 코드 대신 실행되는 코드
         } catch( ArithmeticExeption ) {
              e.printStackTrace();
         }
  • 해당 메서드에 throws Exception 사용 - 예외가 발생할 경우 Exception 클래스에 맡긴다.
public class Exception {
     private BufferedReader br = null;
     public static void main(String[] args) throws Exception {
          br.read();
     }
}

- 무조건 수행되어야 하는 코드가 있을 때

  • finally: 예외에 상관없이 무조건 수행되는 구문
try {
     br.read();
} catch (IndexOutOfBoundsException e) {     // 배열범위가 넘어갔을 때
     e.printStackTrace();       // Exception이 발생한 이유와 위치
} finally {
    ShoubeRun();     // 예외에 상관없이 무조건 수행된다.
}

2. DateTime

- Calendar, Date : 날짜와 시간을 받아옴

- SimpleDateFormat: 원하는 형식대로 날짜와 시간 재구성

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateTime1 {
     public static void main(String[] args) {
          MyTimer mt = new MyTimer();
          mt.go();
     }
}

class MyTimer {
     public void go() {
          Calendar c = Calendar.getInstance();     // getInstance(): 클래스 1회성 사용 (다른곳에 넘겨주기 위한 용도)
          Date date = c.getTime();      // 날짜와 시간이 ms단위로 저장

          // 보기 편한 형태로 날짜와 시간을 구성
          SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
          String date1 = sdf.format(date);

          // 출력
          System.out.println(date1);
------------------------------------------------------------------------
출력값: 2022-12-08 16:07:23

3. Random

- 랜덤으로 숫자를 선택하는 2가지 방법

- 2가지 방법 모두 기본 0.0 ~ 1.0의 범위를 가진다.

  • Math.random();
    double num1 = math.random();     // 0.0 ~ 0.999999999 
    int num2 = math.random()*100;     // 0 ~ 99
  • Random 메서드 객체화
    Random rand = new Random();
    double num1 = rand.nextInt();     // 0.0 ~ 0.999999999
    int num2 = rand.nextInt(100);     // 0 ~ 99
<예제: 입력받은 두 수 사이에서 랜덤을 돌려 출력>
class MyRandom {
     public void go() {
          Random rand = new Random();
          Scanner sc = new Scanner(System in);
          int num1 = 0, num2 = 0;

          System.out.print("최소 범위를 입력하세요 >>");
          num1 = Integer.parseInt(sc.nextLine());
          System.out.print("최대 범위를 입력하세요 >>");
          num2 = Integer.parseInt(sc.nextLine());
    
          int result1 = (int)(Math.random()*(num2-num1+1) + num1;
          int result2 = rand.nextInt(num2-num1+1) + num1;
  
          System.out.println(result2);
     }
}

4. Enum**

- 한정된 개수의 값들을 하나로 묶어서 사용하기 위한 방식

- 클래스 내부 또는 외부에 생성

- 열거된 순서에 따라 0부터 인덱스값을 가지게 된다.

enum Type {

     타입1, 타입2, 타입3, 타입4

     // 타입1== 0, 타입2 ==1, 타입3 == 3, 타입4 == 3

}

 

MyType [] type = MyType.values();     // eum의 요소들을 순서대로 enum타입의 배열로 리턴. 

 

- 전체보기

for(int i = 0; i<type.length; i++) {

    System.out.println(type[i].name()+", 번호는"+ type[i].ordinal());     

     // name()은 저장한 문자열을, ordinal()은 문자열의 순서를 리턴한다

}

- 빠른 for문으로 전체보기

for(myType t: type) {     // t == type[i]

     System.out.println(t.name() + , "번호는"+ t.ordinal())

}


5. String

- String은 java에서 제공하는 기본자료형이 아닌 클래스이다.

     String str = new String("string");      // 따라서 원래는 이렇게 사용해야 하지만

     String str = "string";                          // 편하게 쓰기 위해 간략화됨

- String 클래스에서 지원해주는 메서드

String str1 = "Hello World"

str1.equals(str) ---------------- 괄호 안의 문자와 같다 true | false
str1.charAt(6) ------------------ 6번째 글자(배열)
str1.indexOf("Wor")----------- 괄호 안 글자들중 첫번째 글자의 배열번호
str1.length() -------------------- str1의 길이
str1.startsWith("Hello") ------ Hello로 시작하는 문자열인가 true | false
str1.contains("World") -------- World를 포함하는 문자열인가 true | false
str1.substring(6, 11) ----------- 6번째 글자 ~ 10번째 글자를 잘라서 출력 (World)
str1.replace("Hello", "Hi") ----- Hello 문자열을 찾아서 Hi로 교체

- String 클래스의 형변환

     기본 자료형끼리의 형변환은 앞에 (자료형)을 붙여주면 된다.

     그러나 String의 형변환은 다른 메서드를 사용한다.

Private String str = "123";
Private int num;
Private double dNum;

1. String -> int | double
num = Integer.parseInt(str);                 // String -> int
dNum = Double.parseDouble(str);      // String -> double

2. int | double -> String
str = Integer.toString(num);       // int -> String
str = Double.toString(dNum);    // double -> String

 

 

'JAVA' 카테고리의 다른 글

JAVA 7주차  (1) 2022.12.15
JAVA 6주차  (0) 2022.12.11
JAVA 4주차  (0) 2022.11.23
JAVA 3주차  (0) 2022.11.16
JAVA 2주차  (0) 2022.11.10

댓글