목차
▶︎ Integer.parseInt()를 사용하기
이 메서드를 사용하면 기본형 정수(primitive type int)로 리턴한다.
문자열에 유효한 숫자를 포함하고 있지 않다면 NumberFormatException
이 출력된다.
그래서 혹시라도 입력을 받는 String을 Integer로 변환할 경우 try-catch
문으로 감싸서 예외상황을 처리해주는것이 좋다.
✔︎ 예시
String str = "44";
try{
int number = Integer.parseInt(str);
System.out.println(number); // output = 44
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
▶︎ Integer.valueOf() 를 사용하기
이 메서드를 사용하면 문자열을 정수 객체(Integer object)로 리턴한다.
이 메서드 역시 try-catch문을 이용해서 예외처리를 해주는것이 좋다.
✔︎ 예시
String str = "44";
try{
Integer number = Integer.valueOf(str);
System.out.println(number); // output = 44
}
catch (NumberFormatException ex){
ex.printStackTrace();
}
다른 방법
👉
위에서 사용한 try-catch를 이용한 검사도 가능하지만 isNumeric()을 이용해서 입력된 문자열이 숫자인지 아닌지 먼저 체크하고 동작할 수 있게 하는 방법도 있다.
public class StringTest {
public static void main(String[] args) {
String str = "44";
String str1 = "44.06";
System.out.println(isNumeric(str));
System.out.println(isNumeric(str1));
}
private static boolean isNumeric(String str){
return str != null && str.matches("[0-9.]+");
}
}