이번에 사용자 정의 예외 처리를 위한 실습 문제들을 풀면서 꽤나 재밌었다. 복습할 겸 그 문제 중 하나를 이 곳에 정리한다.
문제 1: 사용자로부터 입력 받은 문자열을 검사하여 해당 문자열이 공백 문자를 포함하고 있다면 사용자 정의 Exception을 생성한 후 발생시키고, 공백 문자를 포함하지 않았다면 해당 문자열의 영문자 갯수를 리턴 후 출력하여라.
문제 해결 과정 (1):
1-0. String 매개변수를 가지고 int(문자열의 갯수)리턴하는 메소드 작성
1-1. 사용자로부터 문자열 입력받아 input으로 사용(Scanner, nextLine();)
1-2. 해당 문자열을 문자(char)단위로 쪼개기 (charAt())
1-3. 쪼갠 문자들을 문자열의 길이만큼 순차적으로 검사하는 반복문 작성 (for문/.length())
1-4. 영문자 판별 후 참일 시 갯수 합산(Character.isUpperCase&isLowerCase(char)메소드)
1-5. 영문자 갯수 리턴
문제 해결 과정 (2):
2-1. 받아온 문자열이 공백 문자를 포함할 경우 발생시킬 사용자 정의 작성
2-1-1. ~Exception의 이름으로 클래스 생성 후 extends RuntimeException 상속
2-1-2. Generate Constructor from SuperClass
2-2. 1-0~1-5의 과정에 try문 작성
2-3. catch문 작성 (catch(ExceptionName ename)){}
2-4. catch가 실행되었을 때의 return값 작성 (int 리턴 메소드기 때문에 필수)
여기서부터는 내가 실제로 작성한 코드이다:
//메인 바디 클래스
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);
}
}
주의 사항
결과 화면