[Tip] 자바의 Integer.parseInt()

2024. 6. 28. 15:45정리

Integer.parseInt()를 이용해서 String 타입을 int형으로 변환할 수 있다. 

 

public class programmers002 {

	public static void main(String[] args) {
		Solution002 s=new Solution002();
		int answer=s.solution("1234");
		System.out.println(answer);
	}

}
class Solution002 {
    public int solution(String s) {
        int answer = 0;
        
        answer=Integer.parseInt(s);
        
        return answer;
    }
}

 

물론 String에 숫자가 아닌 문자가 들어있으면 java.lang.NumberFormatException: For input string: "a1234"

와 같은 오류가 난다. 하지만.

package algorithm;

public class programmers002 {

	public static void main(String[] args) {
		Solution002 s=new Solution002();
		int answer=s.solution("-1234");
		System.out.println(answer);
	}
}

 

다음과 같이 - 부호를 적용한 숫자는

// -1234 를 제대로 출력한다.

+부호를 넣으면 출력할 때 +를 제외한다. 

'정리' 카테고리의 다른 글

[Tip] 자바의 remove()  (0) 2024.05.10
[Tip] 자바의 substring()  (0) 2024.05.09
[Regex] 정규 표현식 정리  (0) 2024.05.04
[Git] 명령어 정리  (4) 2024.05.02