Для нашей домашней работы я должен принять объекты Chair
и добавить их к DoublyLinkedList
, которые мы сделали; его нужно сортировать по алфавиту, если стиль одинаковый в алфавитном порядке, мы сортируем по цветуNullPointerException with while loop using compareTo
Когда я пытаюсь пройти цикл, я продолжаю получать NullPointerException
.
public void add(Chair element){
if(isEmpty() || first.object.style.compareTo(element.style) > 0 || (first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) >= 0){
addFirst(element);
}else if(first.object.style.compareTo(element.style) <= 0){
Node temp = first;
Node insert = new Node(); insert.object = element;
while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs
if(temp.hasNext())
temp = temp.next;
while(temp.object.style.compareTo(element.style) == 0 && temp.object.color.compareTo(element.color) <= 0)
if(temp.hasNext())
temp = temp.next;
insert.prev = temp.prev;
insert.next = temp;
temp.prev.next = insert;
temp.prev = insert;
}
}
Это код, где я помещал информацию в DoublyLinkedList
try{
FileReader fr = new FileReader(filename);
Scanner sc = new Scanner(fr);
String[] temp;
while(sc.hasNext()){
temp = sc.nextLine().split(" ");
if(temp[0].equals("Bed")){}
else if(temp[0].equals("Table")){
// tables.add(new Table(Integer.parseInt(temp[1]), Integer.parseInt(temp[2]), Integer.parseInt(temp[3]), temp[4]));
}else if(temp[0].equals("Desk")){}
else if(temp[0].equals("Chair")){
chairs.add(new Chair(temp[1], temp[2]));
}else if(temp[0].equals("Bookshelves")){}
else{
color = temp[0];
}
}
while(!chairs.isEmpty())
System.out.println(chairs.removeFirst().info());
System.out.println();
//while(!tables.isEmpty())
// System.out.println(tables.removeFirst().info());
}catch(Exception e){e.printStackTrace();}
Это класс DoublyLinkedList, что я сделал: класс CDoublyLinkedList { Node первый, последний;
public CDoublyLinkedList(){
first = new Node(); last = new Node();
first.prev = last.next = null;
first.object = last.object = null;
first.next = last;
last.prev = first;
}
public boolean isEmpty(){
return first.object == null;
}
public void addFirst(Chair element){
Node insert = new Node();
insert.object = element;
insert.prev = null;
insert.next = first;
first.prev = insert;
first = insert;
}
public void add(Chair element){
if(isEmpty() || first.object.style.compareTo(element.style) > 0 || (first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) >= 0){
addFirst(element);
}else if(first.object.style.compareTo(element.style) <= 0){
Node temp = first;
Node insert = new Node(); insert.object = element;
while(first.object.style.compareTo(element.style) <= 0)
if(temp.hasNext())
temp = temp.next;
while(first.object.style.compareTo(element.style) == 0 && first.object.color.compareTo(element.color) <= 0)
if(temp.hasNext())
temp = temp.next;
insert.prev = temp.prev;
insert.next = temp;
temp.prev.next = insert;
temp.prev = insert;
}
}
public Chair removeFirst(){
Chair tobedeleted = first.object;
Node temp = first.next;
first = temp;
first.prev = null;
return tobedeleted;
}
private class Node{
Node next, prev;
Chair object;
public boolean hasNext(){
return next != null;
}
}
}
Класс Председатель:
class Chair extends Furniture{
public String style, color;
public Chair(String s, String c){
style = s; color = c;
}
public String toString(){
return color;
}
public String getType(){
return "Chair";
}
public String info(){
return (color+", "+style);
}
}
Может кто-то пожалуйста, объясните мне, почему я получаю эту ошибку? Спасибо!
EDIT:
while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs
chairs.add(new Chair(temp[1], temp[2]));
java.lang.NullPointerException
at CDoublyLinkedList.add(Furnish2SS.java:119)
at Furnish2SS.main(Furnish2SS.java:23)
java.lang.NullPointerException
at CDoublyLinkedList.add(Furnish2SS.java:119)
at Furnish2SS.main(Furnish2SS.java:23)
EDIT2: РЕШИТЬ!
я изменил свое время цикла на:
while(temp.object != null && element != null && (temp.object.compareTo(element) == 0 || temp.object.compareTo(element) == -1))
Причина я получил ошибку, потому что я не проверял на null
каждой итерации.
Один или многие из ваших внутренних объектов кажутся нулевыми, или объект или стиль попробуйте поместить цикл в try catch, чтобы получить внутреннее исключение. – legrandviking
Вы получаете ошибку, потому что что-то пусто. Чтобы узнать, что, посмотрите на стек и посмотрите, в какой строке говорится, что произошло исключение. – trutheality
Существует объект, который упоминается в проекте, который не был создан или установлен в null. Отлаживайте программу и, пожалуйста, сообщите нам, в какой строке находится ваша ошибка. Это может даже помочь вам решить вашу собственную проблему. – parion