HOWTO · Java

Java에서 문자열이 숫자인지 확인하는 방법

이 게시물은 Java에서 문자열이 숫자인지 여부를 확인하는 것입니다.

이 페이지의 내용

이 튜토리얼에서는 Java에서 문자열이 숫자인지 확인하는 방법을 소개하고이를 이해하기위한 몇 가지 예제 코드를 나열합니다.

정규식, Double클래스, Character클래스 또는 Java 8 기능적 접근 방식 등을 사용하여 숫자 문자열을 확인하는 방법에는 여러 가지가 있습니다.

Java에서 문자열이 숫자인지 확인

‘문자열’은 숫자 (유효한 숫자)가 포함 된 경우에만 숫자입니다. 예를 들어"123"은 유효한 숫자 문자열이지만"123a"에는 알파벳이 포함되어 있으므로 유효한 숫자 문자열이 아닙니다.

숫자 문자열을 확인하려면regex를 인수로 사용하고true 또는false 부울 값을 반환하는String 클래스의matched()메서드를 사용할 수 있습니다.

public class SimpleTesting {
  public static void main(String[] args) {
    String str = "123";
    boolean isNumeric = str.matches("[+-]?\\d*(\\.\\d+)?");
    System.out.println(isNumeric);
    str = "121xy";
    isNumeric = str.matches("[+-]?\\d*(\\.\\d+)?");
    System.out.println(isNumeric);
    str = "0x234";
    isNumeric = str.matches("[+-]?\\d*(\\.\\d+)?");
    System.out.println(isNumeric);
  }
}

출력:

true
false
false

Java에서 Class클래스를 사용하여 문자열이 숫자인지 확인

Character래스의 isDigit()메서드를 사용하여 루프의 각 문자를 확인할 수 있습니다. true또는 false값을 반환합니다.

public class SimpleTesting {
  public static void main(String[] args) {
    String str = "1123";
    boolean isNumeric = true;
    for (int i = 0; i < str.length(); i++) {
      if (!Character.isDigit(str.charAt(i))) {
        isNumeric = false;
      }
    }
    System.out.println(isNumeric);
  }
}

출력:

true

Java에서 Apache 라이브러리를 사용하여 문자열이 숫자인지 확인

Apache를 사용하는 경우StringUtils 클래스의isNumeric()메서드를 사용할 수 있습니다.이 메서드는 숫자 시퀀스가 ​​포함 된 경우true를 반환합니다.

import org.apache.commons.lang3.StringUtils;

public class SimpleTesting {
  public static void main(String[] args) {
    String str = "1123";
    boolean isNumeric = StringUtils.isNumeric(str);
    System.out.println(isNumeric);
    str = "123xyz";
    isNumeric = StringUtils.isNumeric(str);
    System.out.println(isNumeric);
  }
}

출력:

true
false

Java에서 Double클래스를 사용하여 문자열이 숫자인지 확인

Double 클래스의parseDouble()메서드를 사용하여 문자열을 double로 변환하고 double 유형 값을 반환 할 수 있습니다. 구문 분석 할 수없는 경우 예외가 발생합니다.

public class SimpleTesting {
  public static void main(String[] args) {
    String str = "1123";
    try {
      Double.parseDouble(str);
      System.out.println("It is a numerical string");
    } catch (NumberFormatException e) {
      System.out.println("It is not a numerical string");
    }
  }
}

출력:

It is a numerical string

Java 8에서 문자열이 숫자인지 확인

Java 8 이상 버전을 사용하는 경우이 예제를 사용하여 숫자 문자열을 확인할 수 있습니다. 여기서Character 클래스의isDigit()메서드는allMatch()에 메서드 참조로 전달됩니다.

public class SimpleTesting {
  public static void main(String[] args) {
    String str = "1123";
    boolean isNumeric = str.chars().allMatch(Character::isDigit);
    System.out.println(isNumeric);
    str = "ab234";
    isNumeric = str.chars().allMatch(Character::isDigit);
    System.out.println(isNumeric);
  }
}

출력:

true
false