반응형

*예외처리

1. try ~ catch

try {

}
catch(Exception e) {
}

 

2. throws 

- 방법1
public class ExceptionExam{
    public int get50thItem(int []array) throws ArrayIndexOutOfBoundsException {    
        return  array[49];
    }
}

- 방법2 
public class ExceptionExam{
    public int get50thItem(int []array){
        if(array.length < 50){
            throw new IllegalArgumentException();
        }
    return  array[49];
    }
}

 

3. 사용자 정의 Exception

- Checked exception 
Exception 클래스를 상속받은 경우 Checked exception이 됩니다. 
이 경우, 반드시 오류를 처리해야 하며 만약 예외처리 하지 않으면 컴파일 오류를 발생시킵니다. 

- Unchecked exception
RuntimeException을 상속받는 경우 Unchecked exception이 됩니다. 
이 경우에는 예외처리를 하지 않아도 컴파일시에 오류를 발생시키지 않습니다.
반응형
반응형

*삼항 연산자

hour < 12? "오전" : "오후";
- hour가 12보다 작으면 오전, 아니면 오후 출력

 

*switch문

import java.util.Calendar;
public class SwitchExam {
    public static void main(String[] args) {
        // month에는 오늘이 몇 월인지 들어 있습니다.
        int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
        String season = "";
        // switch문을 이용해서 season이 오늘은 어떤 계절인지 나타내게 만들어보세요.
        switch (month) {
            case 12:
            case 1:
            case 2:
                season = "겨울";
                break;
            case 3:
            case 4:
            case 5:
                season = "봄";
                break;
            case 6:
            case 7:
            case 8:
                season = "여름";
                break;
            case 9:
            case 10:
            case 11:
                season = "가을";
                break;
        }
        
        System.out.println("지금은 " + month + "월이고, " + season + "입니다.");
    }
}

 

*for each문

public class ForEachExam {
    public static void main(String[] args) {
        int [] array = {1, 5, 3, 6, 7};
        //for each문을 이용해서 array의 값을 한 줄씩 출력하세요
        for (int arr : array ) {
            System.out.println(arr);
        }
        
    }
}

 

*문자열 붙이기/자르기

public class StringExam {
    public static void main(String[] args) {
        String str1 = "안녕하세요. ";
        String str2 = "벌써 여기까지 오셨네요. 끝까지 화이팅!!";
        
        String concatResult;
        String substringResult;
        
        // 아래쪽에 코드를 작성하세요.
        concatResult = str1.concat(str2);
        
        substringResult = str1.substring(2);
        
        
        // 이 아래는 정답 확인을 위한 코드입니다. 수정하지 마세요.
        System.out.println(concatResult);
        System.out.println(substringResult);
    }
}
반응형

+ Recent posts