[자바 실수] Cannot make a static reference to the non-static field 오류

오서영·2022년 4월 22일
0

JAVA 실수 모음

목록 보기
9/10
post-thumbnail

🏷️오류

Cannot make a static reference to the non-static field 라는 오류가 떴다.

코드는 아래와 같았다.

public class ArrayPassingEx {
	 void printCharArray(char[] c) {
		// char[] 배열을 전달받아 출력하는 메소드
		for ( char k: c) {
			System.out.print(k);
		}
		System.out.println();
	}
	
	void replaceSpace(char[] c) {
		// 메소드와 배열의 공백 문자를 콤마로 대치하는 메소드
		for(int i = 0 ; i<c.length; i++) {
			if(c[i] == ' ') {
				c[i] = ',';
			}
		}
	}

	public static void main(String[] args) {
		// char형 배열 선언 및 초기화
		char c[] = {'T','h','i','s',' ','i','s',' ','a',' ','p','e','n','c','i','l','.'};
		
		// printCharArray 메소드로 출력
		printCharArray(c);
				
		// replaceSpace 메소드로 콤마 대치 및 출력
		replaceSpace(c);
		printCharArray(c);
	}
}

🏷️원인과 해결

원인

컴파일 순서와 관련된 오류였다. static 메소드가 아닌 경우, 이를 호출해도 정의되지 않았기 때문에 메모리에 올라가 있지 않다.

해결방법

메소드를 모두 static으로 바꾸어주면 처음부터 메모리에 올라가게 된다.

아래와 같이 말이다.

public class ArrayPassingEx {
	 static void printCharArray(char[] c) {
		// char[] 배열을 전달받아 출력하는 메소드
		for ( char k: c) {
			System.out.print(k);
		}
		System.out.println();
	}
	
	static void replaceSpace(char[] c) {
		// 메소드와 배열의 공백 문자를 콤마로 대치하는 메소드
		for(int i = 0 ; i<c.length; i++) {
			if(c[i] == ' ') {
				c[i] = ',';
			}
		}
	}

	public static void main(String[] args) {
		// char형 배열 선언 및 초기화
		char c[] = {'T','h','i','s',' ','i','s',' ','a',' ','p','e','n','c','i','l','.'};
		
		// printCharArray 메소드로 출력
		printCharArray(c);
				
		// replaceSpace 메소드로 콤마 대치 및 출력
		replaceSpace(c);
		printCharArray(c);
	}
}

참고

https://wookoa.tistory.com/80

profile
개발과 보안에 관심 있는 대학생입니다😎

0개의 댓글