↓IDFormatTest 클래스(main 바깥)↓
public class IDFormatTest {
static Scanner input = new Scanner(System.in); //userid입력받을 스캐너 생성
private String userID; //userID 객체 선언;
public String getUserID() { //userID Getter 생성
return userID;
}
//userID Setter 생성
public void setUserID(String userID) throws IDFormatException { //throws로 IDFormatException에서 예외처리하도록 미룸.
if (userID == null) { //예외 원인
throw new IDFormatException("아이디는 null 일 수 없습니다.");
} else if (userID.length() < 8 || userID.length() > 20) {
throw new IDFormatException("아이디는 8자 이상 20자 이하만 가능합니다.");
}
this.userID = userID; // 어쨌건 this.userID = userID 넣어줄거임.
}
↓IDFormatTest의 main메소드(try-catch 없는 버전)↓
public static void main(String[] args) {
IDFormatTest test = new IDFormatTest(); //자기자신클래스의 객체를 써먹을라고 객체 호출
String IDuser; //위에서 만든 setUserID에 받아주려고 필드하나 선언
IDuser = input.next(); //IDuser에 입력받은 값을 넣는다
test.setUserID(IDuser); //setUserID에 IDuser로 입력받은 값을 넣어준다.
System.out.println(test.getUserID() + "회원가입 완료");
} //그리고 setUserID->getUserID 된게 출력하게끔 하는 내용..
}
↓IDFormatTest의 main메소드(try-catch 추가한 버전)↓
public static void main(String[] args) {
IDFormatTest test = new IDFormatTest();
String IDuser;
try { //여기서부터 예외가 발생할수도 있을것같은 까슬까슬한 느낌이 들어서 try로 감싸준다!
IDuser = input.next();
test.setUserID(IDuser);
} catch (IDFormatException ie) { //어떤예외? 바로 IDFormatException예외 말이지.. 내용은 위에 있더^^
System.out.println(ie.getMessage()); //getMessage --> 이 message가 Exception의 그...message.
//getMessage는 Exception의 메소드이다.
//발생한 예외에 대한 세부 정보를 문자열 형태로 반환해주는 역할을 하는 메소드이다. 그래서 그 문자열(message)에 값을 넣어주려고 super를 해준것이다
} catch (Exception e) { //저거말고 다른 걸러지지않은 애들은 Exception 예외가 처리해줄것이다
System.out.println("예외 발생 프로그램 다시 시작");
}
System.out.println(test.getUserID() + "회원가입 완료");
}
↓IDFormatException클래스↓
public class IDFormatException extends Exception{
public IDFormatException(String message){
super(message);
}
//이거는... Exception 클래스를 일단 상속 받았다.
//그래서 Exception의 message객체를 super를 써서 값을 message에 담으려고.. 담아서 message 써먹으려고, 라고 이해중.
//Exception의 기능들을 쓰려고 그냥 가져왔다고 한다^^
//저 message는 예외처리할때 메시지를 담아준다
}
반응형
'Java 개인공부' 카테고리의 다른 글
| 클래스 - 인스턴스 (0) | 2024.01.07 |
|---|---|
| 배열(Array), 리스트(List) (0) | 2024.01.07 |
| 예외, try-catch-finally (1) | 2024.01.07 |
| 자바 - 다형성, 추상클래스, 인터페이스 (0) | 2024.01.07 |
| 클래스 - 상속 (0) | 2024.01.07 |