Original article: Java String to Int – How to Convert a String to an Integer

문자열 객체(object)들은 문자들의 열로 표현된다.

스윙(Java Swing)을 써 본 사람이라면, 거기에 있는 그래픽 사용자 인터페이스에서 입력 값을 가져오기 위해 JTextField나 JTextArea같은 컴포넌트가 쓰이는 것을 봤을 것이다. 이런 컴포넌트들은 우리가 필요한 입력 값을 문자열 형태로 가져온다.

스윙을 이용해서 간단한 계산기를 만든다고 하자. 그럼 문자열(string)을 정수(integer)로 바꾸는 법을 알아야한다. 그러면 물음표가 떠오른다 - 문자열(string)을 정수(integer)로 어떻게 변환할까?

자바에서 문자열을 정수로 변환하기 위해서는 두가지 방법, Interger.valueOf()Integer.parseInt() 이 있다.

1. Integer.parseInt() 를 사용하는 법

이 메소드는 문자열을 기본형 정수 (primitive type int)로 리턴한다. 문자열이 유효한 숫자를 포함하지 않는다면 NumberFormatException이 쓰로우 된다.

그렇기 때문에 문자열을 int로 바꿀때에는 항상 try-catch문으로 코드를 감싸서 이 익셉션을 처리해야 한다.

Integer.parseInt() 를 써서 문자열을 int로 바꾸는 이 예시를 보자.

  String str = "25";
        try{
            int number = Integer.parseInt(str);
            System.out.println(number); // output = 25
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

이제 입력값에 유효하지 않은 정수를 대입해 본다.

    	String str = "25T";
        try{
            int number = Integer.parseInt(str);
            System.out.println(number);
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

위에 있는 코드에서는 25T 를 정수로 변환하려고 한다. 이는 유효한 입력값이 아니다. 그렇기 때문에 NumberFormatException을 쓰로우하게 된다.

위에 있는 코드의 결과값은 이렇다:

java.lang.NumberFormatException: For input string: "25T"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.parseInt(Integer.java:615)
	at OOP.StringTest.main(StringTest.java:51)

다음으로는 Integer.valueOf() 를 사용해서 문자열을 정수로 바꾸는 법을 살펴보자.

2. Interger.valueOf() 를 사용하는 법

이 방법은 문자열을 정수 객체(integer object)로 리턴한다. 자바 도큐멘테이션을 보면 Integer.valueOf() 는 정수 객체를 리턴한다고 나온다. new Interger(Integer.parseInt(s)) 와 동일한 셈이다.

Integer.valueOf() 메소드를 try-catch문과 함께 사용하는 코드 예시를 보자.

        String str = "25";
        try{
            Integer number = Integer.valueOf(str);
            System.out.println(number); // output = 25
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

이번에는 입력값에 유효하지 않은 정수를 넣어보자.

     String str = "25TA";
        try{
            Integer number = Integer.valueOf(str);
            System.out.println(number);
        }
        catch (NumberFormatException ex){
            ex.printStackTrace();
        }

앞서 봤던 예시와 마찬가지로 이 코드도 익셉션을 쓰로우 할 것이다.

위에 있는 코드의 결과 값은 이렇다.

java.lang.NumberFormatException: For input string: "25TA"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.valueOf(Integer.java:766)
	at OOP.StringTest.main(StringTest.java:42)

위에서 본 메소드들을 쓰기 전에 먼저 입력된 문자열이 숫자인지 아닌지 확인하는 메소드를 만들어서 쓸 수도 있다.

입력된 문자열이 숫자인지 아닌지 확인하는 간단한 메소드를 만들어보았다.

public class StringTest {
    public static void main(String[] args) {
        String str = "25";
        String str1 = "25.06";
        System.out.println(isNumeric(str));
        System.out.println(isNumeric(str1));
    }

    private static boolean isNumeric(String str){
        return str != null && str.matches("[0-9.]+");
    }
}

결과값은 이렇다:

true
true

isNumeric() 메소드는 전달인자(argument)로 문자열을 받는다. 그리고 전달인자가 null 인지 아닌지를 확인한다. 그 다음에는 0부터 9사이에 있는 숫자들이나 소수점이 있는지 matches() 메소드를 써서 확인한다.

위의 방법은 문자열에서 숫자값을 확인하기 위한 간단한 예시이고, 유스케이스에 따라서 또 다른 방법으로는 정규표현식(regular expression)을 쓸 수도 있는데 (이 포스트에서는 다루지 않겠지만) 구글 검색을 추천한다.

입력된 문자열이 숫자인지 아닌지 먼저 체크를 한 후에 그 문자열을 숫자로 변환하는 것이 정석이다.

Thank you for reading.

Post image by 🇸🇮 Janko Ferlič on Unsplash

You can connect with me on Medium.

Happy Coding!