未正确初始化的对象数组

时间:2012-04-29 19:03:40

标签: java arrays generics object nullpointerexception

使用此代码,我尝试将包含数据的文件加载到对象数组中。我没有正确地对象中的字段,因为当我运行此代码时,我得到一个NullPointerException。数组在那里,甚至是正确的大小,但字段没有初始化。我该如何解决这个问题?

以下是代码:

public class aJob {
  public int job;
  {
    job = 0;
  }
  public int dead;
  {
    dead = 0;
  }
  public int profit;
  {
    profit = 0;
  }
}

public class Main {
  public static void main(String[]args) throws IOException {
    File local = readLines();
    Scanner getlength = new Scanner(local);
    int lines = 0; 

    while (getlength.hasNextLine()) {
      String junk = getlength.nextLine();
      lines++;
    }
    getlength.close();

    Scanner jobfile = new Scanner(local);  // check if empty                            

    aJob list[] = new aJob[lines];
    aJob schedule[] = new aJob[lines];
    int index = 0;
    list[index].job = jobfile.nextInt();
  }

  public static File readLines() throws IOException 
  {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
      // ignore exceptions and continue
    }

    JFileChooser chooser = new JFileChooser();
    try {
      int code = chooser.showOpenDialog(null);
      if (code == JFileChooser.APPROVE_OPTION) {
        return chooser.getSelectedFile(); 
      }
    } catch (Exception f) {
      f.printStackTrace();
      System.out.println("File Error exiting now.");
      System.exit(1);
    }
    System.out.println("No file selected exiting now.");
    System.exit(0);
    return null;
  }
}

3 个答案:

答案 0 :(得分:5)

声明一个数组是不够的。您必须使用对象实例填充它。

aJob list[] = new aJob[lines];
aJob schedule[] = new aJob[lines];

for (int i = 0; i < lines; i++){ list[i] = new aJob(); schedule[i] = new aJob(); }

答案 1 :(得分:4)

问题是数组的元素没有被初始化,即仍为空。

aJob list[] = new aJob[lines]; // creates an array with null values.
for(int i=0;i<lines;i++) list[i] = new aJob(); // creates elements.

答案 2 :(得分:0)

另一种可能性是您可以使用ArrayList或LinkedList代替程序中的数组。

例如,

ArrayList<aJob> list = new ArrayList<aJob>(lines);
ArrayList<aJob> schedule = new ArrayList<aJob>(lines);

int index = 0;
list.add(0, new aJob(jobFile.nextInt());

做同样的工作。最后一行创建一个新的aJob对象,其值从scanner对象中拉出,然后将其插入到位置0。

虽然数组是一个简单的结构,但使用List可以提供更大的灵活性,特别是如果你不知道你将要制作多少个aJob元素。数组要求在instanciation时定义大小,但List可以增长以处理新元素。

相关问题