×

Loading...
Ad by
  • 技多不压身,工到自然成:安省技工证书特训班,点击咨询报名!
Ad by
  • 技多不压身,工到自然成:安省技工证书特训班,点击咨询报名!

为什么会提示Exception in thread "main" java.lang.NullPointerException?在线等.谢谢

运行后提示Exception in thread "main" java.lang.NullPointerException.
Array应该是可以是任何类型的吧.感觉定义成一个class地类型应该没问题呀.

public class CustArray {
Customer [] custArray;
public CustArray() {

for (int j=0; j<custArray.length; j++){
custArray[j].arrivalTime=j;
custArray[j].length=2*j;
}

for (int j=0; j<custArray.length; j++)
System.out.println("custArray"+j+".arrival time: "+custArray[j].arrivalTime+".length: "+custArray[j].length);
}

public static void main(String[] args) {
new CustArray();

}
class Customer {

double arrivalTime;
double length;
double serviceTime;
}

}
Report

Replies, comments and Discussions:

  • 工作学习 / IT技术讨论 / 为什么会提示Exception in thread "main" java.lang.NullPointerException?在线等.谢谢
    运行后提示Exception in thread "main" java.lang.NullPointerException.
    Array应该是可以是任何类型的吧.感觉定义成一个class地类型应该没问题呀.

    public class CustArray {
    Customer [] custArray;
    public CustArray() {

    for (int j=0; j<custArray.length; j++){
    custArray[j].arrivalTime=j;
    custArray[j].length=2*j;
    }

    for (int j=0; j<custArray.length; j++)
    System.out.println("custArray"+j+".arrival time: "+custArray[j].arrivalTime+".length: "+custArray[j].length);
    }

    public static void main(String[] args) {
    new CustArray();

    }
    class Customer {

    double arrivalTime;
    double length;
    double serviceTime;
    }

    }
    • you defined custArray but never assign a value to it, so it is null. The system can not get the value custArray.length.
      • 我在开始一经初始话这个数组了.不是吗? for (int j=0; j<custArray.length; j++){custArray[j].arrivalTime=j;custArray[j].length=2*j;}
        • In Java, array should be created in this way: Customer [] custArray = new Customer[10];
        • 你的程序有两个错误,都会引起NullPointerException
          1、如yuanml所描述,数组没有初始化;
          2、数组元素没有初始化;
          正确程序应该如下:
          Customer[] custArray = new Customer[COUNT];
          for(int j = 0; i < custArray.length; j++)
          {
          custArray[j] = new Customer();
          custArray[j].arrivalTime = j;
          custArray[j].length = 2 * j;
          }
        • 如果我事先没法知道数组里有多少成员,怎么办?
          • try to use dynamic container instead of array in this case: like ArrayList, Vector, ...
          • 用 ArrayList 是最方便的
          • ArrayList比Vector效率高一些,但要自己作同步。如果不存在同步问题,就用它吧。