문자열을 숫자로 바꿔주는 Integer.parseInt()를 사용한다.
<간단한 예시 코드>
public class StringToInteger {
public static void main(String[] args) {
String strInt = "1234";
int test = Integer.parseInt(strInt);
System.out.println(test); // 1234
}
}
문자를 숫자로 변환하는 것도 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
}
}