K
K
Koshkasobaka2021-01-07 22:36:38
Java
Koshkasobaka, 2021-01-07 22:36:38

Why does InvocationTargetException appear?

Hello, I have a SudokuGenerator class, in the constructor to which, among other things, I pass an instance of the SudokuStorage class. In the fillStorage() method, I create a Sudoku instance and pass it to the sudokuStorage.add(Sudoku) method to put it in Mapy. But the point is that any use of storage in the add() method throws an InvocationTargetException. Without storage everything works.. what am I doing wrong?

public class SudokuGenerator {

    private BoardFactory boardFactory;
    private CellHider cellHider;
    private Sudokustorage sudokuStorage;
// тут геттеры-сеттеры

    public SudokuGenerator(BoardFactory boardFactory, CellHider cellHider, SudokuStorage sudokuStorage) {
        this.boardFactory = boardFactory;
        this.cellHider = cellHider;
        this.sudokuStorage = sudokuStorage;
    }


    public void fillStorage() {
       for (int i = 0; i < 100; i++) {
            Sudoku sudoku = new Sudoku(cellHider.makeBoardWithHiddenCells(boardFactory.generateBoard()));
            sudokuStorage.add(sudoku);
        }
    }
}




public class SudokuStorage {
    private HashMap<Level, ArrayList<Sudoku>> storage;

   public HashMap<Level, ArrayList<Sudoku>> getStorage() {
       return storage;
    }

    public void setStorage() { this.storage = storage; }

    public SudokuStorage() {
        HashMap<Level, ArrayList<Sudoku>> storage = new HashMap<>();
    }


    public void add(Sudoku sudoku) {
        if (storage.containsKey(sudoku.getLevel())) {             
            ArrayList <Sudoku> list = storage.get(sudoku.getLevel());
            list.add(sudoku);
            storage.put(sudoku.getLevel(), list);
        } else {
            ArrayList<Sudoku> list = new ArrayList<>();
            list.add(sudoku);
            storage.put(sudoku.getLevel(), list);
        } 
    

 
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-01-07
@Koshkasobaka

First, you would attach the stack trace with the error. It would be clear what is happening there.
Secondly, something strange is happening in the constructor: for some reason, the local variable storage is created and initialized. If you want to initialize a class variable, it's better to write it like this:

private HashMap<Level, ArrayList<Sudoku>> storage = new HashMap<>();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question