자바 문자, 문자열 숫자로 타입 변환 .valueOf(), Integer.parseInt() 사용법 및 간단한 예시 코드 - 개발새발자 작성 일기

개발새발자·2023년 10월 29일
1

자바 개념

목록 보기
12/15

1. 문자열을 숫자로 변환하기

2. 문자를 숫자로 변환하기



1. 문자열(String)을 숫자(Integer)로 변환

문자열을 숫자로 바꿔주는 Integer.parseInt()를 사용한다.

<간단한 예시 코드>

public class StringToInteger {
    public static void main(String[] args) {
        String strInt = "1234";
        int test = Integer.parseInt(strInt);
        System.out.println(test); // 1234
    }
}

2 . 문자(Char)를 숫자(Integer)로 변환

문자를 숫자로 변환하는 것도 Integer.parseInt()를 사용하면 되지 않을까

컴파일 오류가 뜬다

Integer.parseInt()는 문자열을 숫자로 변환해주는 함수이기 때문에 문자는 바로 Integer.parseInt()를 쓸 수 없다

그렇다면 어떤 방법들이 있을까
(1) 문자를 새로운 문자열 변수에 저장 한 후 숫자로 변환
(2) 문자 그대로 숫자로 변환
(3) 문자 타입을 문자열로 바꾸기

<간단한 예시 코드>

public class CharToInteger {
    public static void main(String[] args) {

        // (1) 문자를 새로운 문자열 변수에 저장하고 숫자로 변환
        char ch2 = '2';
        String ch2str = String.valueOf(ch2);
        System.out.println(Integer.parseInt(ch2str)); // 2

        // (2) 문자 그대로 숫자로 반환
        System.out.println((int) ch2 - '0'); // 2

        // (3) 문자 타입을 문자열로 반환
        String ch1 = "1";
        System.out.println(Integer.parseInt(ch1)); // 1
        
    }
}
profile
바삭하고 촉촉한 쿠키로 살자

0개의 댓글