parseInt (1)

💻 Programming/Java

[Java] 숫자 판별하기

 

자바에서 숫자 판별하기

 

Java의 스트링이 숫자(정수, int)인지 판단하기 위한 방법 두 가지를 소개합니다

 

 

1) 스트링의 각 문자를 하나하나 순회하면서 ascii 코드 값을 비교하는 방법

 

첫 번째로 소개해드릴 방법은 입력받은 문자열(스트링)의 각 문자가 0~9 ascii 코드값 사이에 있는 char인지를 판별하는 방법입니다.

 

0~9의 ascii 코드값은 십진수로 48~57 입니다.

 

따라서 String을 char[]로 변환한 다음 loop를 돌면서 각 char가 48~57사이의 값인지를 판단하여 숫자인지를 판별합니다.

 

코드는 아래와 같습니다.

String str = "not a number";

boolean isNumber = true;

for(char c : str.toCharArray()) {

  if(c >= 48 && c<= 57) {
        continue;
  } else {
        isNumber = false;
        break;
  }
}
System.out.println("Is string a number ? answer: " + isNumber);

 

2) Integer.parseInt 를 이용하는 방법

 

두 번째 방법은 Integer.parseInt 메서드를 이용하는 방법입니다.

 

parseInt 메서드에 대한 javadoc 문서에는 아래와 같이 설명이 나와있습니다.

public static int parseInt(String s)
                    throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to theparseInt(java.lang.String, int) method.

 

Parameters:
s - a String containing the int representation to be parsed
Returns:
the integer value represented by the argument in decimal.
Throws:
NumberFormatException - if the string does not contain a parsable integer.

 

 

즉, 문자로 표현된 숫자를 입력받아 int로 return하는데요

입력받은 스트링이 숫자가 아닐 경우 NumberFormatException예외를 발생시킵니다.

 

따라서 위 메서드를 사용하여 NumberFormatException의 발생 여부에 따라 해당 스트링이 숫자인지 아닌지를 판별할 수 있습니다.

 

이 방식을 사용한 코드는 아래와 같습니다.

 

String str = "421303";

boolean isNumber = false;

try {

Integer.parseInt(str);

isNumber = true;

} catch (NumberFormatException e) {

// do nothing

}

System.out.println("Is string a number ? answer: " + isNumber);

 

Integer 뿐만 아니라 다른 wrapper 클래스들에도 Long.parseLong, Double.parseDouble 메서드들이 있으니 참고하시기 바랍니다.

 

 

위 두 가지 방법 외에 또 좋은 방법이 있으신 분들 제보받습니다 ㅎ

 

내용이 도움이 되셨다면 공감 누르고 가주세요~