java - 对象数组未正确初始化

标签 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;
  }
}

最佳答案

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

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(); }

关于java - 对象数组未正确初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10375044/

相关文章:

java - Vaadin 谷歌描述

java - 具有多个子项的树的数组中的通用类型

javac:需要不兼容的类型:类名<TYPEPARAM> 找到:类名<java.lang.Object>

generics - F# 从对象而非类型实例化泛型类型

java - AWS API Gateway 集成响应

java - 如何使我的自定义迭代器适用于每个列表?

java - Jackson JsonSchemaGenerator - 如何将模式获取为字符串

php - 有两个数组的foreach循环

JavaScript $.get ("curl.php",{ 数组值

f# - 在不同的泛型实例中实现相同的接口(interface)