0

このコードを使用して、データを含むファイルをオブジェクトの配列にロードしようとしています。このコードを実行すると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;
  }
}
4

3 に答える 3

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(); }
于 2012-04-29T19:07:13.733 に答える
4

問題は、配列の要素が初期化されていないことです。つまり、まだ null です。

aJob list[] = new aJob[lines]; // creates an array with null values.
for(int i=0;i<lines;i++) list[i] = new aJob(); // creates elements.
于 2012-04-29T19:07:13.187 に答える
0

もう 1 つの可能性は、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 オブジェクトを作成し、位置 0 に挿入します。

配列は単純な構造ですが、リストを使用すると柔軟性が高まります。特に、作成する aJob 要素の数がわからない場合はそうです。配列ではインスタンス化時にサイズを定義する必要がありますが、リストには新しい要素を処理するために拡張する機能があります。

于 2012-04-29T19:27:02.490 に答える