Я попытался создать массив, содержащий deques, но когда я пытался получить доступ к элементу dequeues с помощью offerLast (), я получил NULPOINTEREXCEPTION. Я понимаю, что это потому, что он равен нулю, но есть ли способы заставить его работать.
public static void main(String[] args) {
Kattio io = new Kattio(System.in, System.out);
int n = io.getInt();
String[] wordList = new String[n];
// this part is where I try to create an array of deques
Deque[] index = new Deque[n];
System.out.println(index);
for (int i = 0; i < n; i++) {
String string = io.getWord();
wordList[i] = string;
}
int last = 0;
for (int i = 0; i < n - 1; i++) {
int firstStr = io.getInt();
int secondStr = io.getInt();
Deque<Integer> firstPosition = new ArrayDeque<>();
Deque<Integer> secPosition = new ArrayDeque<>();
firstPosition = index[firstStr-1];
secPosition = index[secondStr-1];
if (firstPosition != null && secPosition != null) {
for (Integer num : secPosition) {
firstPosition.offerLast(num);}
} else if (firstPosition != null) {
firstPosition.offerLast(secondStr-1);
} else if (secPosition != null) {
firstPosition.offerLast(firstStr-1);
for (Integer num : secPosition) {
firstPosition.offerLast(num);}
} else {
// this part is where the exception is thrown
firstPosition.offerLast(firstStr-1);
firstPosition.offerLast(secondStr-1);
}
last = firstStr-1;
}
System.out.println(index[last]);
System.out.println(wordList);
io.close();
}