[완료] 간단한 자바 구문 한 번만 봐 주십시요.

linuxgeek의 이미지

옛날에 C++로 만든 프로그램을 android에 포팅할려고 하는데 자바를 해 본적이 없어서 작은 구문에도 애를 먹네요.

=============== CODE ===================

public class Test
{
    class Tes
    {
        int a;
    };
 
    public static void main(String[] args)
    {
        Tes t[][] = new Tes[6][9];
 
        for (int i = 0 ; i < 6 ; i++)
        {
            for (int j = 0 ; j < 9 ; j++)
            {
                t[i][j].a = 0;
            }
        }
    }
}

==========================================

위의 코드는 컴파일은 잘 되는데 실행을 하면 아래와 같은 에러를 냅니다. 이유가 뭔가요?

---------- Java Excute ----------
Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:16)

creativeidler의 이미지

자바에서 객체는 명시적으로 생성자를 호출해줘야 생깁니다. 배열 선언으로는 객체가 생기지 않죠.

public class Test
{
    class Tes
    {
        int a;
    };
 
    public static void main(String[] args)
    {
        Tes t[][] = new Tes[6][9];
 
        for (int i = 0 ; i < 6 ; i++)
        {
            for (int j = 0 ; j < 9 ; j++)
            {
                t[i][j] = new Tes();
                t[i][j].a = 0;
            }
        }
    }
}
linuxgeek의 이미지

감사합니다.

그런데 고쳐 주신 코드를 실행해 보니 컴파일 도중

---------- Java Compiler ----------
Test.java:16: non-static variable this cannot be referenced from a static context
				t[i][j] = new Tes();

^

이란 에러가 뜹니다. 이건 또 다른 문제 같은데 뭐가 잘못된 걸까요?

===================================================================
8-bit

===================================================================
8-bit

linuxgeek의 이미지

main 메소드가 static이기 때문이라는군요.

답변 주신 분들께 감사 드립니다.

===================================================================
8-bit

===================================================================
8-bit

bookgekgom의 이미지

자바의 모든 오브젝트는 다이내믹 으로 잡아줍니다. 즉

MyClass *myClass = new MyClass(); //C++ 에서
MyClass myClass = new MyClass(); //자바 에서

public class Test{
class Tes{
int a;
};

public static void main(String[] args){
Tes t[][] = new Tes[6][9];

for (int i = 0 ; i < Tes.length; i++){ //length 이용...
for (int j = 0 ; j < Tes[i].length; j++){
t[i][j] = new Tes();//사용전 생성
t[i][j].a = 0;
}
}
}
}

이정도려나염...

---------------------------------------------------------------------------------------------------------------
루비 온 레일즈로 만들고 있는 홈페이지 입니다.

http://jihwankim.co.nr

여러 프로그램 소스들이 있습니다.

필요하신분은 받아가세요.

linuxgeek의 이미지

감사합니다.

그런데 마찬가지로

Test.java:11: non-static variable this cannot be referenced from a static context

란 에러가 뜨네요.

===================================================================
8-bit

===================================================================
8-bit