이번에 사용자 정의 예외 처리를 위한 실습 문제들을 풀면서 꽤나 재밌었다. 복습할 겸 그 문제 중 하나를 이 곳에 정리한다.
문제 1: 사용자로부터 입력 받은 문자열을 검사하여 해당 문자열이 공백 문자를 포함하고 있다면 사용자 정의 Exception을 생성한 후 발생시키고, 공백 문자를 포함하지 않았다면 해당 문자열의 영문자 갯수를 리턴 후 출력하여라.
여기서부터는 내가 실제로 작성한 코드이다:
//메인 바디 클래스
package com.exception.charcheck;
public class Characterprocess {
public int countAlpha(String s) {
char[] arr = new char[s.length()];
int count = 0;
try {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
throw new CharCheckException(s);
}
}
System.out.println("입력하신 문자열은 "+s+"입니다!");
if(Character.isUpperCase(s.charAt(i)) || Character.isLowerCase(s.charAt(i))) {
count++;
}
} System.out.println("입력하신 문자열에서 영문자는 총 "+count+"개 있습니다.");
return s.length();
} catch (CharCheckException cc) {
System.out.println("체크할 문자열 안에 공백 포함할 수 없습니다.");
cc.printStackTrace();
}
return 0;
}
public Characterprocess() {
super();
}
}
//사용자 정의 Exception 클래스
package com.exception.charcheck;
public class CharCheckException extends RuntimeException{
public CharCheckException() {
super();
}
public CharCheckException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public CharCheckException(String message, Throwable cause) {
super(message, cause);
}
public CharCheckException(String message) {
super(message);
}
public CharCheckException(Throwable cause) {
super(cause);
}
}
//실행 클래스
package com.exception.charcheck;
import java.util.Scanner;
public class Run {
Scanner sc = new Scanner(System.in);
Characterprocess cp = new Characterprocess();
public static void main(String[] args) {
Run r = new Run();
r.test1();
}
public void test1() {
System.out.println("사용할 문자열을 하나 입력하세요.");
String txt = sc.nextLine();
cp.countAlpha(txt);
}
}
주의 사항
결과 화면