-
※문제. 키보드로 문자열을 입력 받아 countAlpha 메소드로 문자열 전달, 영문자 몇 개인지 카운트해서 리턴 (단, 공백문자가 있으면 CharCheckException 발생)
더보기1234567891011121314151617public class CharacterProcess {public int countAlpha(String s) {String[] str = s.split(" ");if (str.length > 1) {throw new CharCheckException("체크할 문자열 안에 공백 포함할 수 없습니다.");} else {int cnt = 0;for (int i = 0; i < s.length(); i++) {char ch = s.charAt(i);if (Character.isUpperCase(ch) || Character.isLowerCase(ch))cnt++;}return cnt;}}}cs 12345678910111213141516171819202122public class Run {Scanner sc = new Scanner(System.in);public static void main(String[] args) {Run run = new Run();run.test1();}public void test1() {CharacterProcess cp = new CharacterProcess();try {System.out.print("문자열을 입력하세요 > ");String s = sc.nextLine();System.out.println("영문자의 개수 : " + cp.countAlpha(s));}catch(CharCheckException e) {e.printStackTrace();}}}cs 여기에 임의의 CharCheckException 클래스를 만들어 RuntimeException에 상속시켰다.
split메소드를 이용해서 공백을 기준으로 나누도록 한 뒤, 해당 배열의 크기가 1 이상이면 공백이 있는 것으로 간주하고 예외를 발생시켰다.
더보기선생님이 쓴 방법들.
charAt메소드랑 indexOf메소드.
1234567891011121314public class CharacterProcess {public int countAlpha(String s) throws CharCheckException {int cnt = 0;for(int i=0; i<s.length(); i++) {if(Character.isUpperCase(s.charAt(i)) || Character.isLowerCase(s.charAt(i)))cnt++;if(s.charAt(i) == ' ')throw new CharCheckException("체크할 문자열 안에 공백 포함할 수 없습니다.");}return cnt;}}cs 1234567891011121314public class CharacterProcess {public int countAlpha(String s) throws CharCheckException {if(s.indexOf(" ") > -1)throw new CharCheckException("체크할 문자열 안에 공백 포함할 수 없습니다.");int cnt = 0;for(int i=0; i<s.length(); i++) {if(Character.isUpperCase(s.charAt(i)) || Character.isLowerCase(s.charAt(i)))cnt++;}return cnt;}}cs '혼자 있는 방 > Java' 카테고리의 다른 글
Homework(11) (0) 2021.07.08 실기_Test(2) (0) 2021.07.06 필기_Test(2) (0) 2021.07.05 Homework(10) (0) 2021.07.02 Homework(9) (0) 2021.07.01 댓글