2015-01-03 79 views
0

我仍然开始学习OOP,并且这个错误一直在我的代码中弹出;说Exception in thread "main" java.lang.NullPointerExceptionNullPointerException java错误

public class SlumbookDriver{ 
    public static void main(String args[]){ 
     Slumbook[] contacts = new Slumbook[19]; 
     ... // index is an int and is the value of the index of the array 
     ... // i feed it to a function "void viewEntry" that just shows 
      // the other attributes of the class Slumbook 
     viewEntry(index, contacts); 
    } 
} 

然后我具备的功能VIEWENTRY

public static void viewEntry(int index, Slumbook[] contacts){ 
    Scanner sc = new Scanner(System.in); 
    if(index == 0){ 
     System.out.println("Array is empty"); 
    } 
    else{ 
     String id = contacts[index].getIdNo(); 
     System.out.println("Please enter ID number"); 
     String idNo = sc.next();  
     if(id != idNo){ 
      while(id != idNo && index != -1){ 
       index--; 
       id = contacts[index].getIdNo(); 
      } 
      if(index == -1){ 
       System.out.println("ID does not exist"); 
       return; //terminate action since the ID number does not exist 
      } 
     } 
     System.out.println(contacts[index].viewDetails()); 
    } 
} 
+0

你可以发布更多的代码,以及堆栈跟踪打印与例外?这将有助于查明问题。 – Malt

回答

2

你只是初始化数组

Slumbook[] contacts = new Slumbook[19]; 

而不是它的内容,因此你会得到一个NullPointerException当您访问数组元素,如下所示:

String id = contacts[index].getIdNo(); 

当您创建一个对象数组时,数组中的对象不会被初始化,您需要在使用它们之前使用new运算符初始化它们。类似这样的:

contacts[index] = new Slumbook(); 
+0

是的,我已经做到了这一点,以填充另一个函数中的对象我的数组,但错误仍然弹出 – user253938

+0

@ user253938你可能不会持有适当的引用。发布完整的代码。 –

+0

谢谢,但它似乎只有索引变为0时弹出错误(我不知道为什么它发生,虽然联系人[0]已分配值,所以它不能为NULL),以解决它我只是保留接触[0]为空,离开程序,并开始与阵列上的联系人[1],现在它运行完美 – user253938

0

这里的问题是你已经初始化了一个SlumBook数组,但是数组的内容需要初始化。 对于初学者来说,只是初始化内容:

for (int i = 0; i < contacts.length; i++) 
{ 
    contacts[i] = new SlumBook(); 
} 

做到这一点的方法viewEntry(int, SlumBook[])

0

一个NullPointerException发生在你试图访问一个字段或引用的方法使用接触过,但该引用为null 。

例如

Slumbook a = null; 
a.getIdNo(); // NullPointerException 

相同,如果你有一个数组

Slumbook [] data = new Slumbook[N]; 
data[i].getIdNo(); /// NPE 

第二个例子会抛出NPE如果包含在i位置的基准恰好是空发生。

当你得到一个异常堆栈跟踪显示,它包含文件名和确切行号(大部分时间)在异常发生