2009-06-10 2 views
0

저는 컴퓨터, 서버를 추가하고 이더넷 포트로 두 개의 객체를 연결할 수있는 간단한 시뮬레이션 네트워크를 자바에 넣고 있습니다. 이것은 "this.etherPort.addElement (t);를 호출 할 때 null 포인터 예외가 발생하는 곳입니다."자바에서 null 포인터 예외로 도움을 받으십시오.

import java.util.Vector; 

public class Server extends Computer{ 

    public Vector<Ethernet> etherPort; 

    public void addPort(Ethernet t) 
    { 
    this.etherPort.addElement(t); 
    } 
} 

이 코드를 사용하여 새로운 이더넷 개체를 만들 때이 코드가 실행 :

public class Ethernet { 

public Computer terminal1, terminal2; public int volume; public Ethernet(Computer term, Server term2) { this.terminal1 = term; this.terminal2 = (Computer) term2; if(term != null) { term.addPort(this); } if(term2 != null) { term2.addPort(this); } } }

답변

10

당신은 당신의 etherPort 멤버를 실체화해야합니다

public class Server extends Computer{ 

    public Vector<Ethernet> etherPort = new Vector<Ethernet>(); 

    public void addPort(Ethernet t) 
    { 
     this.etherPort.addElement(t); 
    } 
} 

당신 포트 추가가()하지만, 당신의 컴퓨터 생성자에서 호출하는 방법을 재정의되지 않았는지 확인해야합니다. 문맥을 감안할 때 안전하다고 가정합니다 ( 컴퓨터에 addPort() 메소드가 없음). 코멘트에 아래에 언급 한 바와 같이

, 그것은 컨테이너 구현을 제한하지 않는 인터페이스를 사용하는 것이 일반적으로 더 나은 : 당신은 더 나은 대신

Vector<Ethernet> 

List<Ethernet> 

로 etherPort를 선언 할 것

을 사용하고 Vector 관련 addElement 메소드 대신 etherPort.add (element)를 사용하십시오.

2

etherPort은 null입니다. 당신은 분명히 실제 벡터로 초기화하지 않을 것입니다. 당신이 원하는 것 같아요 :

public class Server extends Computer{ 

    public Vector<Ethernet> etherPort; 

    public Server() 
    { 
     etherPort = new Vector<Ethernet>(); 
    } 

    public void addPort(Ethernet t) 
    { 
     this.etherPort.addElement(t); 
    } 
} 
3

벡터를 초기화하지 않았습니다. 해야합니다

public Vector<Ethernet> etherPort = new Vector<Ethernet>(); 
+0

비공개 최종 목록이어야합니다. etherPorts = new ArrayList (); 결승전에서이 오류를 발견했을 것입니다. –

관련 문제