본문 바로가기
Java/Java with Error

[해결 방법] java.lang.Error

by HJ0216 2023. 2. 16.

 기본 환경: IDE: Eclipse, Language: Java

 

 

발생 Exception

Java에서 다음 Source Code를 실행할 경우,

public class RandomChar {

	public static void main(String[] args) {
        char[] ar = new char[50];
		int[] count = new int[26]; // Default=0

		for(int i = 0; i<ar.length; i++) {
			ar[i] = (char)(Math.random()*26) + 65;
			if(i%10==0) {System.out.println();}
			System.out.print(ar[i] + " ");

			for(int j=0; j<count.length; j++) {
				if(j == (ar[i]-65)) {count[j]++;};
			} // for inner
			
		} // for outer
    }
}

⭐ java.lang.Error: Unresolved compilation problem:

→  Type mismatch: cannot convert from int to char 발생

 

 

Exception 원인

cast char값에 int를 더해줄 수 없음

ar[i] = (char)(Math.random()*26) + 65;

계산 순서

Math.random()*26 : int

(char) (Math.random()*26): char

(char) (Math.random()*26)+65: char + int

char type으로 강제 형 변환 후, int를 직접적으로 더해줄 수 없음

 

⭐ 일반적으로 char + int -> int 변환이 이뤄지는데, 해당 source code에서만 예외적으로 실행되지 않음

public class CharIntDouble {

	public static void main(String[] args) {

        int a = 70;
        char b = 'A';
        double c = 66.7;

        System.out.println(a);
        System.out.println(b);
        System.out.println(a+2);
        System.out.println(b+2);
        System.out.println((char)a+2);
        System.out.println((int)c);
        System.out.println((char)c);
        System.out.println((char)c+10);

    }
}

/*
Result
70
A
72
67 : char + int = int
72 : char + int = int
66
B
76 : char + int = int
*/

 

 

해결 방법

+65를 괄호안으로 넣어 계산 순서 변경

public class delete {

	public static void main(String[] args) {
        char[] ar = new char[50];
		int[] count = new int[26]; // Default=0

		for(int i = 0; i<ar.length; i++) {
			ar[i] = (char)(Math.random()*26 + 65);
			if(i%10==0) {System.out.println();}
			System.out.print(ar[i] + " ");

			for(int j=0; j<count.length; j++) {
				if(j == (ar[i]-65)) {count[j]++;};
			} // for inner
			
		} // for outer
    }
}

/*
Result
Q Q C P N B P G O J 
O C Z G F G U O A F
Q H S Q U K E U Q R
L I Y E Y K M O K H
R Y Z C S S F Z Q N

*/