[코딩 오류 노트] 변수 이름 중복, 데이터 타입, 자동 형 변환, 상수 선언 후 값 변경 등
1. 변수 이름 중복
코드
int b = 30;
int b = 40;
오류 메시지
duplicate local variable b
2. 데이터 타입에서 저장 가능한 값 범위 초과
코드
byte a = 128;
System.out.println(a);
오류 메시지
Type mismatch: cannot convert from int to byte
3. 자동 형변환 오류
코드
byte a = 127;
int b = a;
System.out.println(b);
float c = b;
System.out.println(c);
int d = c;
System.out.println(d);
오류 메시지
Type mismatch: cannot convert from float to int
float는 실수형 데이터 타입이기 때문에 int로 변환하려면 강제변환(캐스팅) 해야 한다.
4. 상수 선언 후 값 변경
코드
final double PI = 3.14;
PI = 3.15;
System.out.println(PI);
오류 메시지
The final local variable PI cannot be assigned. It must be blank and not using a compound assignment
final로 상수를 선언하면 프로그램 실행 중에 변경할 수 없다.
5. 숫자연산 된 char타입 출력
코드
char t = 'A';
t = (t+3);
System.out.println(t);
오류 메시지
Type mismatch: cannot convert from int to char
char타입은 문자형이지만 컴퓨터가 인식할 수 있는 형태인 숫자로 저장된다. 때문에 숫자 연산을 할 수 있는데, 연산을 하면 숫자로 다뤄진다.
* char t = 'A';
t = (char)(t+3);
System.out.println(t);
=>E 출력
* char t = 'A';
t = (char)(t+3);
System.out.println((char) (t+3));
=>G 출력
숫자연산 된 값을 다시 char타입으로 강제변환하면 char타입으로 출력할 수 있다.
6. 비교연산자를 동시에 두 개 사용
코드
80<=point<90
오류 메시지
The operator < is undefined for the argument type(s) boolean, int
*80 <= point && point<90을 사용하면 정상적으로 연산된다.