Java Error Note

·2021년 7월 10일
1
post-thumbnail

에러노트

  1. 컴파일 오류
  2. 런타임 오류
  3. 논리 오류

자료형을 일치 시키지 않았을 때 - 런타임 오류

  • java.util.IllegalFormatConversionException: d != java.lang.Float
  float data = System.in.read();
  System.out.printf("입력하신 문자는 %d입니다.", data);
  • 발생 이유

    • 변수의 자료형과 입력받을 자료형을 일치 시켜야한다.
  • 해결 방법

    • %d를 %f로 바꿔서 타입을 일치 시켜야 한다.

변수를 중복해서 사용했을 때 - 컴파일 오류

  • Duplicate local variable a
  int a = 100;
  int a = 170;
  • 원인
    • 같은 변수의 이름을 2개 이상 쓸 수 없다.
  • 해법
    • 다른 이름의 변수를 사용한다. (구별 할 수 있도록)

타입을 잘못 선택했을 때 - 컴파일 오류

  • Type mismatch: cannot convert from int to String
  String data = System.in.read();
  • 발생 이유

    • 자료형을 잘못 선택했을 때 오류 발생.
  • 해결 방법

    • String타입을 int타입으로 작성한다.

;을 안썼을 때 - 컴파일 오류

  • Syntax error, insert ";" to complete BlockStatements
  int a = 10
  • 발생 이유

    • 자바는 문장이 종결될 때 끝에 ;를 써야한다.
  • 해결 방법

  int a = 10;
  • 끝에 ;를 작성한다.

대입 값을 안썼을 때 - 컴파일 오류

  • Syntax error on token "=", Expression expected after this token
  int a = ;
  • 발생 이유

    • = 은 대입 연산자이다. 변수에 대입 될 값을 안썼기 때문에 오류가 발생했다.
  • 해결 방법

  int a = 10;
  • 대입 값을 써준다.

값을 정의하지 않은 변수를 대립했을 때 - 컴파일 오류

  • b cannot be resolved to a variable
  int a = b;
  • 발생 이유

    • b를 선언하지 않고 대입했기 때문에 오류 발생.
  • 해결 방법

    int b = 20;
    • 변수 b를 선언과 초기화 시킨다.

""의 짝을 맞춰서 사용하지 않았을 때 - 컴파일 오류

  • String literal is not properly closed by a double-quote
  System.out.println(");
  • 발생 이유

    • " " (double-quote mark)의 짝을 맞춰서 사용하지 않아서 에러
  • 해결 방법

  System.out.println(**"**안녕하세요.**"**);

println에 %s를 사용했을 때 - 컴파일 오류

  • The method println(String) in the type PrintStream is not applicable for the arguments (String, String)
  String name = "다인";
  System.out.println("안녕하세요. 저는 %s입니다.", name);
  • 발생 이유

    • println()메소드에 맞지 않는 형식의 값을 넣어서 오류
  • 해결 방법

  System.out.println("안녕하세요. 저는 " + name + "입니다.");

초기화 시키지 않은 변수를 사용했을 때 - 컴파일 오류

  • The local variable size may not have been initialized
  byte size;
  System.out.println(size);
  • 발생 이유

    • 자바는 변수가 초기화 되지 않은 상태에서 사용이 불가능하다.
  • 해결 방법

  byte size = 230;  
  • 변수에 값을 대입해 초기화 해준다.

변수명을 숫자로 시작했을 때 - 컴파일 오류

  • Syntax error on token "123", delete this token
  byte 123num;
  • 발생 이유

    • 자바는 변수명을 숫자로 시작 불가능하다.
  • 해결 방법

  //변수명을 숫자로 꼭 시작하고 싶다면 _를 사용해준다.
  byte _123num;
  • 자바의 변수명은 영어 + 숫자 + _ 를 조합하여 사용할 수 있다.

변수명을 숫자로 시작했을 때 - 컴파일 오류

  • The literal 1000000000000000 of type int is out of range
  long money = 1000000000000000;
  • 발생 이유

    • 자바의 모든 상수의 자료형은 int이다. int 범위를 벗어난 값을 사용했기 때문에 에러가 발생했다.
  • 해결 방법

  long money = 1000000000000000**L**;
  • 접미어L을 붙여준다.

리터럴에 접미어를 붙이지 않았을때 - 컴파일 오류

  • Type mismatch: cannot convert from double to float

    float f1;
    f1 = 3.14;
  • 발생 이유

    • 자바의 모든 실수형의 기본 자료형은 double이다.
    • float 타입 사용시 리터럴에 접미어F를 붙여준다.
  • 해결 방법

    char m1 = ' ';  
    • 접미어F를 붙여준다.

char형에서 ''빈 문자열을 사용했을 때 - 컴파일 오류

  • Invalid character constant
  char m1 = '';
  • 발생 이유

    • 문자형은 ''안에 반드시 무언가가 표현이 되야한다.
  • 해결 방법

  char m1 = ' ';  
  • 공백문자(blank)로 변수 ch를 초기화 시켜준다.

short형의 변수를 byte형의 변수에 대입했을 때 - 컴파일 오류

  • Type mismatch: cannot convert from short to byte
  short s2 = 10;
  byte b2;
  		
  b2 = s2;
  • 발생 이유

    • short를 byte로 형변환(큰형에서 작은형)하려면 명시적 형변환(byte)을 사용해야한다.
  • 해결 방법

  b2 = (byte)s2;

printf()에 % 사용 할때 - 런타임 오류

  • java.util.IllegalFormatFlagsException: Flags = ' '
  System.out.printf("%d % %d = %d\n", num1, num2, num1 % num2);
  • 발생 이유

    • 어떤 특수한 역할을 하는 문자를 이스케이프하고 싶으면, 보통 같은 문자를 한번 더 적는다. 자바( % ) -> %%
  • 해결 방법

  System.out.printf("%d %% %d = %d\n", num1, num2, num1 % num2);

숫자를 * 곱할때 int타입을 넘는 경우 - 논리 오류

int money1 = 2000000000;
int money2 = 1500000000;

System.out.println("잔액 : " + (money1 + money2)); //잔액 : -794967296
  • 발생 이유

    • 모든 산술 연산의 결과는 항상 자료형이 두 피연산자 중 더 큰 자료형으로 반환된다. (int + int = int)
  • 해결 방법

    System.out.println("잔액 : " + (money1 + (long)money2)); 
    • int + long = long --> 형변환을 해준다.

문자열끼리 비교 시 == 비교연산자 사용 - 논리 오류

String str1 = "홍길동";

String str2 = "홍";
str2 = str2 + "길동";

System.out.println(str1 == str2);
  • 발생 이유

    • 문자열비교는 equals()메소드를 사용해야함!
  • 해결 방법

  System.out.println(str1.equals(str4)); 

int 타입을 equal()메소드로 비교했을때 - 컴파일 오류

  • Cannot invoke equals(String) on the primitive type int
  String address = "서울";
  int num = 5;
  		
  System.out.println(address.equals("서울") && num.equals(5));
  • 발생 이유

    • int 정수형 타입은 비교 연산을 할때는 == 을 사용한다.
    • equal()메소드는 문자열 비교시 사용한다.
  • 해결 방법

    • 문자열끼리 equal()로 비교한다.
  String address = "서울";
  String hair = "긴머리";
  	
  System.out.println(address.equals("서울") && hair.equals("긴머리"));

패키지 파일 경로를 잘못 지정했을 때 - 컴파일 오류

  • The declared package "study.name" does not match the expected package "study.java"
  package study.name;
  • 발생 이유

    • 클래스 파일이 들어있는 패키지의 경로를 다른 패키지로 적었을 때 발생
  • 해결 방법

    • 클래스 파일이 들어있는 패키지의 파일 경로를 맞게 써준다.
  package study.java;

패키지 파일 경로를 잘못 지정했을 때 - 컴파일 오류

  • The declared package "study.name" does not match the expected package "study.java"
  package study.name;
  • 발생 이유

    • 클래스 파일이 들어있는 패키지의 경로를 다른 패키지로 적었을 때 발생
  • 해결 방법

    • 클래스 파일이 들어있는 패키지의 파일 경로를 맞게 써준다.
  package study.java;

if-else에서 else뒤에 ()를 썼을때 - 컴파일 오류

  • The left-hand side of an assignment must be a variable
  if (true) {
  	System.out.println("안녕하세요");
  } else (true){
  	System.out.println("반가워요");
  };
  • 발생 이유

    • if - else문에 else뒤에 ()를 사용했을 때 에러 발생.
  • 해결 방법

    • if문의 값이 false가 되었을 때 실행 시킬 조건식을 사용하고 싶을 경우 if else를 사용한다.
  if (true) {
  	System.out.println("안녕하세요");
  } else if (true){
  	System.out.println("반가워요");
  };

switch문 ()안에 논리형을 썼을 경우 - 컴파일 오류

  • Cannot switch on a value of type boolean. Only convertible int values, strings or enum variables are permitted
  switch (true) {
  	case 3:case 4: case 5:
  		System.out.println("봄입니다.");
  		break;
  	case 6: case 7: case 8:
  		System.out.println("여름입니다.");
  		break;
  	case 9: case 10: case 11:
  			System.out.println("가을입니다.");
  		break;
  	default :
  			System.out.println("겨울입니다.");
  • 발생 이유

    • switch문의 소괄호( ) 안에는 값(변수, 상수, 수식, 메서드)을 넣을 수 있으며, 그 값의 결과는 정수 또는 문자(열)만이 허용한다.
  • 해결 방법

    • 정수를 입력받는 정수형 변수를 ()조건식 안에 넣어준다.
  int month = scan.nextInt();
  		
  switch (month) {
  	case 3:case 4: case 5:
  		System.out.println("봄입니다.");
  		break;
  	case 6: case 7: case 8:
  		System.out.println("여름입니다.");
  		break;
  	case 9: case 10: case 11:
  		System.out.println("가을입니다.");
  		break;
  	default :
  		System.out.println("겨울입니다.");

반환타입에 맞는 반환값을 안썼을 경우 - 컴파일 오류

  • This method must return a result of type int
  public static int test() {}
  • 발생 이유

    • 반환값을 int타입을 써야한다.
  • 해결 방법

    • 정수를 입력받는 정수형 변수를 ()조건식 안에 넣어준다.
  public static int test(int a, int b) {
  		return a+b;
  }

void를 썼는데 return을 한 경우 - 컴파일 오류

  • Duplicate method test() in type Ex15_Method
  public static void test() {
  	return 100;
  }
  • 발생 이유

    • 돌려주는 값이 없어서 void를 적었는데, return값을 넣으면 에러가 뜬다.
  • 해결 방법

    • 리턴의 유무와 리턴타입과 반환타입의 자료형이 맞아야한다
  public static int test() {
  		
  	System.out.println("테스트1");
  		
  return 100;

return 뒤에 코드를 쓴 경우 - 컴파일 오류

  • Unreachable code
  public static int test() {
  		
  	System.out.println("테스트1");
  		
  	return 100;
  		
  	//리턴 뒤에 코드를 적으면 안된다.
  	//System.out.println("테스트2"); //Unreachable code
  }
  • 발생 이유

    • return문을 만났을때 , 메서드가 실행을 종료하고 호출된 곳으로 돌아간다.
  • 해결 방법

    • return 뒤에는 코드를 적으면 안됨.
  public static int test() {
  		
  	System.out.println("테스트1");
  	
      System.out.println("테스트2");
      
  	return 100;
  }

매개변수와 같은 변수를 메소드 안에 선언했을 경우 - 컴파일 오류

  • Duplicate local variable name
  public static void hi(String name) {
  		
  	String name = "홍길동"; 
  		
  	System.out.printf("%s님 안녕하세요\n", name);
  }
  • 발생 이유

    • 매개변수와 같은 변수를 메소드 안에 선언했을 경우, 같은 메서드를 두 번 선언한 것과 같다.
  • 해결 방법

    • 매개변수로 값을 받아 실행한다.
  public static void hi(String name) {
      System.out.printf("%s님 안녕하세요\n", name);
  }

가인자와 실인자의 갯수가 동일하지 않은 경우 - 컴파일 오류

  • he method hi(String) in the type Ex14_Method is not applicable for the arguments()
  public class Ex14_Method {
  
  	public static void main(String[] args) {
         hi(); 
      }
      public static void hi(String name) { 
      	System.out.printf("%s님 안녕하세요\n", name);
  	}
  }
  • 발생 이유

    • 매개변수 사용시, 가인자와 실인자의 갯수와 자료형이 동일해야한다 .
  • 해결 방법

    • 가인자와 실인자의 갯수와 자료형을 일치 시킨다.
  public class Ex14_Method {
  
  	public static void main(String[] args) {
         hi("홍길동");
      }
      public static void hi(String name) { 
      	System.out.printf("%s님 안녕하세요\n", name);
  	}
  }

시각(Calendar) - 시각(Calendar)를 했을 경우 - 컴파일 오류

  • The operator - is undefined for the argument type(s) java.util.Calendar, java.util.Calendar
  Calendar now = Calendar.getInstance(); //현재 시각
  Calendar birthday = Calendar.getInstance();//태어난 시각
  
  birthday.set(1997, 8, 25, 13, 30, 50);
  System.out.println(now - birthday); //에러
  • 발생 이유

    • 산술연산자 -> 피연산자는 원시형밖에 가질 수 없다. (특히 숫자형만 가능)
    • 참조형은 피연산자가 될 수 없다.
  • 해결 방법

    • now.getTimeInMillis()를 사용해서 구한다.
  Calendar now = Calendar.getInstance(); //현재 시각
  Calendar birthday = Calendar.getInstance();//태어난 시각
  
  birthday.set(1997, 8, 25, 13, 30, 50);
  
  long nowTick = now.getTimeInMillis();
  long birthTick = birthday.getTimeInMillis();
  
  System.out.println((nowTick - birthTick) / 1000 / 60 / 60 / 24);

지역변수를 메소드 밖에서 호출했을 경우 - 컴파일 오류

  • result cannot be resolved to a variable
  int num = 10;
  
  if(num > 0) {
      String result = "통과";
  } 
  
  System.out.println(result); //에러
  • 발생 이유

    • 메소드 내에서 선언한 변수는 본인이 포함된 메서드를 영역으로 삼기 때문에 밖에서 호출할 수 없다.
  • 해결 방법

    • 메서드 외부에서 변수를 초기화 해준다.
  int num = 10;
  String result = " ";
  
  if(num > 0) {
      result = "통과";
  } 
  
  System.out.println(result);

}를 하나 더 적었을 경우 - 컴파일 오류

  • Exception in thread "main" java.lang.Error: Unresolved compilation problem:
  public class Ex22_for {
  
  	public static void main(String[] args) {
          
      }
  }
  } //에러
  • 발생 이유

    • { (열린 괄호)와 }(닫힌 괄호)의 갯수가 같은지 확인해야한다.
  • 해결 방법

    • 괄호가 잘 닫혔는지 확인한다.
  public class Ex22_for {
  
  	public static void main(String[] args) {
          
      }
  }

문자열에서 문자 추출시 없는 문자를 추출했을 경우 - 컴파일 오류

  • java.lang.StringIndexOutOfBoundsException: index 30, length 14
String txt = "안녕하세요. 홍길동입니다.";

char c = txt.charAt(30); //에러 

System.out.println(c);
  • 발생 이유

    • 문자열의 범위를 이외의 문자를 호출했기 때문에 에러
  • 해결 방법

    • 문자열의 범위 내의 문자를 호출한다.
  String txt = "안녕하세요. 홍길동입니다.";
  
  char c = txt.charAt(3);
  
  System.out.println(c);

배열에 없는 인덱스에 첨자를 사용하려고 했을 때 - 런타임 오류

  • java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
int[] num = new int[10];

for(int i=0; i<num.length; i++) {
	num[i] = i + 1;
}

System.out.println(num[9]); //에러
  • 발생 이유

    • 배열에 없는 인덱스를 사용하려고 했을때 생기는 에러
  • 해결 방법

    • 배열 인덱스 범위 내의 인덱스를 호출한다.
  int[] num = new int[10];
  
  for(int i=0; i<num.length; i++) {
  	num[i] = i + 1;
  }
  
  System.out.println(num[1]);

부모를 안썼는데 재정의 하려고 하는 경우 - 컴파일 오류

  • The method aaa() of type BBB must override or implement a supertype method
class AAA {
	public int a;
	public void aaa() {
		System.out.println("부모 행동");
	}
}


class BBB { //에러 
	public int b;
	public void bbb() {
		
	}
	
	public void aaa() {
		System.out.println("자식행동");
	}
}
  • 발생 이유

    • 오버라이드는 상속을 했을때 메소드를 재정의 할때 쓰인다.
  • 해결 방법

    • 상속받는 부모를 명시한다.
  class AAA {
  	public int a;
  	public void aaa() {
  		System.out.println("부모 행동");
  	}
  }
  
  
  class BBB extends AAA {
  	public int b;
  	public void bbb() {
  		
  	}
  	
  	public void aaa() {
  		System.out.println("자식행동");
  	}
  }

final 메소드를 상속해서 오버라이딩 했을 경우 - 컴파일 오류

  • Cannot override the final method from FinalParent
final class FinalParent {
    public final void test() {
        System.out.println("부모 행동");
    }

}



class FinalChild extends FinalParent {

	//고치지 말라는 메소드를 고쳤다. -> 예기치못한 문제 발생 가능성!!
	@Override
	public void test() {
		System.out.println("자식 행동");
	}
}
  • 발생 이유

    • 고치지 말라는 메소드를 final을 붙여서 만들었는데 오버라이딩 했을 경우 에러 발생
  • 해결 방법

    • 부모 것을 쓸 수밖에 없음... 오버라이딩 불가
  final class FinalParent {
      public final void test() {
          System.out.println("부모 행동");
      }
  
  }
  
  class FinalChild extends FinalParent {
      
  }

메소드의 접근지정자를 private으로 지정하고 다른 클래스에서 호출하는 경우 - 컴파일 오류

  • The method remove(String) from the type MyHashMap is never used locally
private void remove(String key) {
    for(int i = indexKey(key) ; i<this.index-1 ; i++) {
        this.keys[i] = this.keys[i+1];
        this.values[i] = this.values[i+1];
    }
    this.index--;
}
  • 발생 이유

    • private은 같은 클래스 내에서만 사용할 수 있다.
  • 해결 방법

    • publicEhsms protected, (default)를 사용한다.
  public void remove(String key) {
      for(int i = indexKey(key) ; i<this.index-1 ; i++) {
          this.keys[i] = this.keys[i+1];
          this.values[i] = this.values[i+1];
      }
      this.index--;
  }

final 변수의 값을 수정하려고 하는 경우 - 컴파일 오류

  • The final local variable b cannot be assigned.
int a = 10; //일반 변수
final int b = 20; //final 변수
		
System.out.println(a);
System.out.println(b);
		
a = 30;
//b = 40; //에러
  • 발생 이유

    • final 변수는 상수이기때문에 값을 수정할 수 없다.
  • 해결 방법

    • 값을 고정하고 싶지 않다면 일반 변수로 사용해야한다.
    • final 변수명은 전부 대문자로 사용한다. -> 상수임을 명시해줘야한다.
  int a = 10; //일반 변수
  final int B = 20; //final 변수
  		
  System.out.println(a);
  System.out.println(B);
  		
  a = 30;

부모클래스를 자식클래스로 다운캐스팅하려는 경우 - 컴파일 오류

  • java.lang.ClassCastException
Parent p3 = new Parent();
Child c3;

c3 = (Child)p3; //에러
  • 발생 이유

    • 참조형 형변환은 자식 클래스 -> 부모 클래스에만 가능하다.
  • 해결 방법

    • Child -> Child하는 방법을 사용한다.
  Parent p4;
  Child c4 = new Child();
  		
  //업캐스팅
  p4 = c4; //안전
  		
  Child c5;
  		
  //다운캐스팅 -> 가능한 작업(*****)
  //자식클래스 = 부모클래스로 보이지만 실제로는 Child -> Child 한 것(*****)
  		
  c5 = (Child)p4;

ArrayList사용시 다운캐스팅하지 않고 사용할때 - 컴파일 오류

  • The operator * is undefined for the argument type(s) Object, int
ArrayList num2 = new ArrayList();

num2.add(100);
num2.add(200);
num2.add(300);

System.out.println(num2.get(0)*2); //에러
  • 발생 이유

    • Object배열이기 때문에 형변환 후 사용할 수 있다.
  • 해결 방법

    • 다운캐스팅 후 사용한다.
  ArrayList num2 = new ArrayList();
  
  num2.add(100);
  num2.add(200);
  num2.add(300);
  
  System.out.println((int)num2.get(0)*2);
profile
모르면 괴롭고 알면 즐겁다.

0개의 댓글