2015-10-26 3 views
1

Я не уверен, что это за ошибка или почему это происходит. Все, что я нашел в Интернете, не имеет ничего общего с TableViews. Но когда этот метод в моем классе-заключенном получает доступ к моему TableView, он выдает InvocationTargetException. Это мой первый раз, используя TableView.Java InvocationTargetException при заполнении TableView

public int getCellBlock() { 
    for (int i = 0; i < Main.getCellBlocks().size(); i++) //for each cellblock 
     for (int j = 0; j < Main.getCellBlocks().get(i).getCells().size(); j++) //for each cell 
      for (int k = 0; k < Main.getCellBlocks().get(i).getCells().get(j).getInmates().size(); k++) 
       if (Main.getCellBlocks().get(i).getCells().get(j).getInmates().get(k).equals(this.idNum)) { 
        return i; 
       } 
    return -1; 
} 

клеток (имеет два подкласса, но им не доступа к данным в них с описанным выше способом):

import java.io.Serializable; 
import java.util.ArrayList; 

public class Cell implements Serializable { 

private ArrayList<Integer> inmateIdNums; 
private int capacity = 0; 


Cell(int cap){ 
    capacity = cap; 
    inmateIdNums = new ArrayList<>(); 

    for (int i = 0; i < capacity; i++) 
     inmateIdNums.add(null); 

} 

public void add (int idNum){ 
    for (int i = 0; i < capacity; i++){ 
     if (inmateIdNums.get(i) == null) { 
      inmateIdNums.set(i, idNum); 
      break; 
     } 
    } 
} 

public void add (int idNum, int dur){} 

public void add (int idNum, String reason){} 

public ArrayList<Integer> getInmates(){ return inmateIdNums; } 

public int getEmptyBunks(){ 
    int emptyBunks = 0; 

    for (int i = 0; i < inmateIdNums.size(); i++){ 
     if (inmateIdNums.get(i) == null) 
      emptyBunks++; 
    } 

    return emptyBunks; 
} 
} 

тюремного корпуса:

import java.io.Serializable; 
import java.util.ArrayList; 

public class CellBlock implements Serializable{ 

private String name; 
private String type; 
private int capacity; 
private int occupancy = 0; 
private ArrayList<Cell> cells; 

CellBlock(int cap, String nName, String nType, int cellCapacity){ 
    name = nName; 
    type = nType; 
    capacity = cap; 
    cells = new ArrayList<>(capacity); 

    if (type == "Maximum Security" || type == "Minimum Security") { 
     for (int i = 0; i < capacity; i++) 
      cells.add(new Cell(cellCapacity)); 
    } 
    else if(type == "Infirmary"){ 
     for (int i = 0; i < capacity; i++) 
      cells.add(new InfirmaryCell(cellCapacity)); 
    } 
    else if(type == "Isolation"){ 
     for (int i = 0; i < capacity; i++) 
      cells.add(new IsolationCell(cellCapacity)); 
    } 
} 

public void addInmate(int cell, int inmateIdNum){ 
    cells.get(cell-1).add(inmateIdNum); 
    occupancy++; 
} 

public void addInmate(int cell, int inmateIdNum, String reason){ 
    cells.get(cell-1).add(inmateIdNum, reason); 
    occupancy++; 
} 

public void addInmate(int cell, int inmateIdNum, int duration){ 
    cells.get(cell-1).add(inmateIdNum, duration); 
    occupancy++; 
} 

public void removeInmate(int inmateIdNum){ 
    //search for inmate and remove from list 
} 

public ArrayList<Cell> getInmates(){ return cells; } 

public boolean checkCapacity(){ 
    if (capacity > occupancy) 
     return true; 

    return false; 
} 

public ArrayList<Cell> getCells(){ return cells; } 

public ArrayList<String> getOpenCells(){ 
    ArrayList<String> openCells = new ArrayList<>(); 

    for (int i = 0; i < cells.size();i++){ 
     if (cells.get(i).getEmptyBunks() > 0) 
      openCells.add(Integer.toString(i+1)); 
    } 

    return openCells; 
} 
} 

Ошибка:

enter image description here

enter image description here

+0

Причиной является «NullPointerException» в строке 68 Prisoner.java. (Вы должны указать в вопросе, какая строка - строка 68.) Это означает, что вы вызываете метод по ссылке, которая является «null». Поскольку у вас есть код, который объединяет длинные последовательности вызовов методов, вам, вероятно, придется развязать их, чтобы выяснить, что такое null. –

+1

Пожалуйста, не публикуйте скриншоты трассировки стека, вместо этого скопируйте и вставьте текст трассировки стека в свой вопрос. – jewelsea

+0

@jewelsea Я собирался это сделать, но это было так долго (дольше, чем то, что есть на изображениях), и мне не удавалось форматировать все это так, чтобы это было легко на глазах. – Alyssa

ответ

0

Я не уверен, кто это сделал, но я исправил это сам. Петли были прекрасны.

Проблема была одна из двух вещей - сравнение или файлы, в которых я написал информацию (я использую двоичные файлы и ObjectInputStream/ObjectOutputStream).

В конструкторе Cell я имел:

for (int i = 0; i < capacity; i++) 
     inmateIdNums.add(null); 

И чтобы избежать сравнения Integer к null Я изменил его:

for (int i = 0; i < capacity; i++) 
     inmateIdNums.add(0); 

Это не исправить мою проблему. Поэтому я мог только предположить, что кто-то, где по пути что-то пошло не так, когда один из моих файлов был написан, пока это дрянное сравнение продолжалось. В качестве последнего усилия я удалил файлы, с которыми я работал, и запускал свою программу для создания новых файлов и добавления новых записей.

Проблема решена.

Смежные вопросы