For our homework, I have to take in Chair objects and add them to the DoublyLinkedList that we made; it has to be sorted by alphabetical order, if style is the same alphabetically, we sort by color
When I try to go through the loop, I keep getting a 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;
}
}
This is the code where I put the information into the 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();}
This is the DoublyLinkedList class that I've made:
class CDoublyLinkedList{
Node first, last;
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;
}
}
}
The Chair class:
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);
}
}
Can someone please explain to me why I keep getting this error? Thank you!
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: SOLVED!
I changed my while loop to:
while(temp.object != null && element != null && (temp.object.compareTo(element) == 0 || temp.object.compareTo(element) == -1))
The reason I got the error was because I wasn't checking for null every iteration.
You say this is the line of code causing the exception:
while(temp.object.style.compareTo(element.style) <= 0)
You probably should set a debugger breakpoint on that line and use a debugger to determine which of the values is null. But it's hard for me to explain here full instructions on how to setup and use a debugger (that doesn't mean you shouldn't learn! You should. There are lots of tutorials. Google it.) So instead of writing a tutorial on debuggers, I'll just post code that will tell you which variable is null:
if (temp == null) {
System.out.println("temp is null");
} else if (temp.object == null) {
System.out.println("temp.object is null");
} else if (temp.object.style == null) {
System.out.println("temp.object.style is null");
}
if (element == null) {
System.out.println("element is null");
} else if (element.style == null) {
System.out.println("element.style is null");
}
while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs
{
if(temp.hasNext())
temp = temp.next;
if (temp == null) {
System.out.println("loop: temp is null");
} else if (temp.object == null) {
System.out.println("loop: temp.object is null");
} else if (temp.object.style == null) {
System.out.println("loop: temp.object.style is null");
}
if (element == null) {
System.out.println("loop: element is null");
} else if (element.style == null) {
System.out.println("loop: element.style is null");
}
}
If you use the above code statements to replace these three lines of your code:
while(temp.object.style.compareTo(element.style) <= 0) //This is where the nullPointerException occurs
if(temp.hasNext())
temp = temp.next;
you will know which variable is null based on which statement is printed. Hopefully you can take it from there. (The usual way to fix a NullPointerException is to take the steps necessary to ensure the offending null variable actually has a valid, non-null value by the time the program reaches the line of the NullPointerException).
Take a look at addFirst(Chair element). That method is really screwed up. It creates a new Node which contains the correct Chair. It then sets its prev to null. Then it sets next to first. And this is what's causing all of your troubles. Because first points to an empty Node. You end up with this:
first points to your new Node. That one points to a Node which holds no Chair. That one again points to last.
e:
Your whole code looks like you had at least two different approaches on implementing your list and threw them toghether. There are some more errors but since this is homework I guess it's not that bad if you try fixing it first.
If you can't figure out how to correct that, ask here.
PS: Sorry for all of the editing and (un)deleting my answeres (if you noticed). I'm a bit tired and kept causing new errors by fixing old ones until I finally figured out what was the true cause of all this.
Related
I'm getting the name and average of some people, but i need to delete one of them based on his average (the user choses which one to delte), how can i do that?
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String name = input.next();
double avr = input.nextInt();
Node first = new Node(name, avr);
for (int i = 0; i < 4; i++) {
System.out.println("enter name");
name = input.next();
System.out.println("enter avr");
avr = input.nextInt();
Node second = new Node(name, avr);
second.next = first;
first = second;
}
Node temp = first;
double delete;
System.out.println("avr of person you want to delete");
delete = input.nextInt();
while (temp != null) {
if (delete == (temp.avr)) {
//delete
System.out.println("delete this guy");
break;
} else {
temp = temp.next;
}
}
delete = input.nextInt();
if (temp.avr == delete){
first = temp.next;
}
else{
while (temp != null && temp.next != null) {
if (delete == (temp.next.avr)) {
temp.next = temp.next.next;
System.out.println("delete this guy");
break;
} else {
temp = temp.next;
}
}
}
Explanation: In order to delete the relevant node you update its previous node to point to its next.
And, since we're always checking if temp.next == delete, we have to check first if the node that needs to be deleted is the first node and delete it accordingly.
NOTE: The suggested code above should work specifically for the example you supplied. But, in general, I would suggest to always add conditions for all possible cases, such as first == null or the node to be deleted was not found and so on.
Simply traverse the linked-list with two pointers (references). One would search for the node that is to be deleted and the other would be just behind this pointer.
Node prev = null;
Node curr = first;
while((curr != null) && (curr.avr != delete)) {
prev = curr;
curr = curr.next;
}
if(curr == null) {
// not found
}
else if(prev == null) {
// first element
first = first.next;
}
else {
prev.next = curr.next;
}
NOTE: Comparison of doubles for equality doesn't work. You can compare for only less than or greater than. Read about precision issues with respect to double (floating-point) comparisons. I would suggest you use integer for the average in case you have to compare for equality.
I get a NullPointerException when I execute this line:
temp.previous.next = null;
in the last else of the code below.
The Contact class is a Node of a linked List.
Can anyone see what the problem might be?
public Contact delete(){
Scanner keyboard =new Scanner(System.in);
Contact temp = first;
System.out.print("Enter a name: ");
String name = keyboard.next();
while (temp != null) {
if (temp.name.equalsIgnoreCase(name)) {
break;
}
temp = temp.next;
}
if (temp == null) {
System.out.println("record not found.");
} else if (count == 1) {
first = null;
last = null;
count--;
return temp;
} else if (count==2) {
if (temp == first) {
temp.next.previous = null;
first = temp;
count--;
return temp;
} else {
first.next = null;
count--;
return temp;
}
} else if (count >= 3) {
if (temp == first) {
temp.next.previous = null;
first = temp.next;
count--;
return temp;
} else {
if (temp.next != null) {
temp.next.previous =temp.previous;
temp.previous.next = temp.next;
count--;
return temp;
} else {
temp.previous.next = null; // <-- NPE here!
count--;
return temp;
}
}
}
return temp;
}
You are assigning null to temp.previous.next, but nowhere do you check that temp.previous is not null.
Further, you initialize temp with first, which presumably (being "first") has no previous node - ie temp.previous would probably be null.
Thus it is likely you are getting a NullPointerException attempting to execute the problem code.
QED.
I'm trying to add items to a double linked list and I'm try to add them in the correct order defined by comparing their strings.
public boolean add(Book book)
{
Node current = new Node(book);
if(firstNode == null)
{
firstNode = current;
lastNode = current;
numElements++;
return true;
}
else
{
Node tempNode = firstNode;
int val = -1;
while(tempNode != null)
{
if(tempNode.bookElement.compareTo(book) > 0)
{
val = 1;
break;
}
else if(tempNode.bookElement.compareTo(book) == 0)
return false;
else
{
val = -1;
tempNode = tempNode.next;
}
}
if(val > 0)
{
System.out.println("next: " + tempNode.bookElement.getISBN());
current.next = tempNode;
if(tempNode == firstNode)
tempNode.previous = current;
if(current.previous == null)
firstNode = current;
numElements++;
return true;
}
else
{
current.previous = tempNode;
tempNode.next = current;
lastNode = current;
numElements++;
return true;
}
}
}
and here is how i'm adding the objects:
Book[] books = new Book[4];
books[0] = new Book("a", "charles g", "book1");
books[1] = new Book("b", "michael b", "book2");
books[2] = new Book("c", "james k", "book3");
books[3] = new Book("d", "gsdgsdgg g", "book4");
BookList booklist = new BookList();
booklist.add(books[0]);
booklist.add(books[1]);
booklist.add(books[2]);
booklist.add(books[3]);
The objects are compared using the String compareTo on the first parameter i.e "a" or "b"
At the moment I can get the the list to sort properly if I switch the order i.e "a" = "d", "b" = "c" etc, but if I keep it in it the way it is now and try sort i get a null pointer on:
tempNode.next = current;
if I make the line
while(tempNode != null)
to
while(tempNode.next != null)
then the list sorts in order and I can keep it as a,b,c,d. But I'm wanting to be able to sort it correctly regardless of the order I add them in so I think there is something very wrong in the way I'm adding them.
EDIT:
I got the list adding backwards so adding d,c,b,a first works as intended since it wasn't checking the if statements in the while block for the first node since the first nodes next was null so I put it into a dowhile so that it checks it, but I am still getting a null pointer when I try to run it normally by a,b,c,d. The null pointer is happening on the while(tempNode.next != null)
do
{
if(tempNode.bookElement.compareTo(book) > 0)
{
val = 1;
break;
}
else if(tempNode.bookElement.compareTo(book) == 0)
return false;
else
{
val = -1;
tempNode = tempNode.next;
}
}
while(tempNode.next != null);
Your current code fails to add nodes to the end of the list, since in that case tempNode becomes null, and tempNode.next gives you NullPointerException.
You should change your condition to while(tempNode.next != null), but if after the loop val < 0, you have to compare current to tempNode, to determine whether current should be inserted before or after tempNode.
I have looked at a lot of other answers on stackoverflow and can't find anything that works, I either get the root, or node1 itself returned, I'm not sure how to do this recursively and have tried it many times all ending the same way. Any help would be greatly appreciated!
Here's my code:
private static Node findLCA(Node node1, Node node2) {
Node temp1 = node1, temp2 = node2, currentLargest = null;
int largestDepth = 0;
boolean found = false;
if(node1 == null || node2 == null){
return null;
} else{
while(found == false){
if(temp1.getParent() != null && temp2.getParent() != null && temp1.getParent() == temp2.getParent() && nodeDepth(temp1.getParent()) > largestDepth){
largestDepth = nodeDepth(temp1.getParent());
currentLargest = temp1;
temp1 = temp1.getParent();
temp2 = temp2.getParent();
} else if(temp1.getParent() != null){
temp1 = temp1.getParent();
} else if(temp2.getParent() != null){
temp2 = temp2.getParent();
}
if(temp1.getParent() == null && temp2.getParent() == null){
found = true;
}
}
if(nodeDepth(temp1) >= largestDepth){
return temp1;
} else{
return currentLargest;
}
}
}
I edited it to make a list of ancestors of each node, but I'm not sure how to go around checking each one to see if the elements in the list's match up since they are usually different sizes.
Heres the new code:
ArrayList<PhyloTreeNode> list1 = new ArrayList<PhyloTreeNode>();
ArrayList<PhyloTreeNode> list2 = new ArrayList<PhyloTreeNode>();
if(node1 == null || node2 == null){
return null;
} else{
if(node1.getParent() != null){
list1.add(node1.getParent());
findLeastCommonAncestor(node1.getParent(), node2);
}
if(node2.getParent() != null){
list2.add(node2.getParent());
findLeastCommonAncestor(node1, node2.getParent());
}
}
We can use recursive post order traversal for computing lowest common ancestor,
Here is my Java implementation
Here a & b are given input data for which i have to find lowest common ancestors.
public static int lowestcommanancestors(Node root,int a,int b){
if(root==null)
return 0;
int x=lowestcommanancestors(root.left,a,b);
int y=lowestcommanancestors(root.right,a,b);
if(x+y==2){
System.out.println(root.getData());
return 0;
}
if(root.getData()==a || root.getData()==b){
return x+y+1;
}
else{
return x+y;
}
}
First i am checking whether given input node presenting in left subtree or not,if yes just return 1 else 0,Similarly for right sub tree.When sum becomes 2 first time that node will be lowest common ancestors.
Tell me if i am wrong or you are getting difficulties to understanding the code
I am running BlueJ as my IDE. For some odd reason I get an error in this line of code:
import javax.swing.*;
public class RotateArrayCircularLL
{
private Node head=null;
// ==================================================================================
public void init()
{
int choice = 0;
while (choice != -1){
choice = Integer.parseInt(JOptionPane.showInputDialog("Enter -1 to stop loop, 1 to continue"));
if(choice == -1)
break;
inputNum();
}
printList();
}
public void inputNum()
{
Node n;
Node temp;
int k;
k = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter a number:"));
n = new Node(k);
if (head == null) {
head = n;
} else {
temp = head;
while (temp.getNext() != null)
temp = temp.getNext();
temp.setNext(n);
}
}
public void printList()
{
Node temp = head;
Node d, e;
int count = Integer.parseInt(JOptionPane.showInputDialog("Enter the value to shift to the right"));
for (int i = 1; i <= count; i++) // Rotates the head
temp = temp.getNext();
for (e = head; e != null; e = e.getNext()){
if (e.getNext() != null)
System.out.print(e.getInfo() + "-");
if (e.getNext() == null)
System.out.print(e.getInfo());
}
for (Node c = temp; c != null && c.getNext() != head; c= c.getNext()){
System.out.print(c.getInfo() + "-");
}
for (d = head; d != null && d.getNext() != temp; d = d.getNext())
{
System.out.print(d.getInfo()+ "-");
}
System.out.println(d.getInfo());
}
}
The error is: Cannot find symbol- method getNext().
The code was working perfectly before but recently my compiler froze and was not responding so I ended the process via Task Manager. Since then it started to act up.
Can anyone explain why it is not working? I don't think that it is my issue, but rather the compilers.
The likely cases are either:
The method getNext() does not exist within the Node class, or
the calling signature of getNext() doesn't match with how it's defined (despite it being an accessor).
I can't say for certain which line of code is causing it, as you haven't provided code for the Node class. However, comb through the Node class and make certain that both getNext() exists, and you're calling it the way you're supposed to (passing valid arguments, and so forth).
Check the xml files. I had the same problem. I was calling a TextView that I previously rename and forgot to change the name.