📅 공부 기간 : 07. 16(화)
주민등록번호(ex. 123456-1234567)에서 '-' 앞 뒤가 다 숫자인지 확인하기
private static boolean isNumeric(String id) {
for(int i=0; i<id.length(); ++i) {
if(!(id.charAt(i) >= '0' && id.charAt(i) <= '9'))
return false;
}
return true;
}
💡 key point : 문자열로 된 숫자도 코드값을 연산자로 비교 가능 ('0' -> 48, '1' -> 49...)
public class JuminValidation {
public static void main(String[] args) {
String jumin = "941225-2123456";
String[] str = jumin.split("-");
if(!(isNumeric(str[0]) && isNumeric(str[1]))) {
System.out.println("# 잘못된 주민번호입니다. (숫자)");
System.exit(0);
}
}
}
'1'-48 => 1'1'-'0' => 1'9'-'0' => 9💡 key point :
문자열 숫자 - '0'
public static void main(String[] args) {
String n = "123"; // ==> 숫자로 변환 (단, charAt())
int size = n.length();
int result = 0;
for (int i = 0; i < size; i++) {
result = result * 10 + (n.charAt(i) - '0');
}
System.out.println(result);
}
String 타입은
Integer.parseInt(n)로도 int로 변환 가능