Reputation: 13
Here are my two classes NameNode and NameList. My problem comes with the print() method in the NameList class. If I have two names lets say "Lee" and "Jim" the output using said method only prints out "Lee". Im not sure if its the append method failing to add to the list or if there is a step error causing tmp to not advance to the next object in the list. Any help is appreciated.
public class NameNode {
private String lastName;
private NameNode next;
public NameNode(String lastName, NameNode toNext)
{
this.lastName = lastName;
this.next = toNext;
}
public String getName()
{
return lastName;
}
public NameNode getNext()
{
return next;
}
public void setNext(NameNode next)
{
this.next = next;
}
public String toString()
{
return lastName;
}
}
public class NameList {
private NameNode names;
public NameList()
{
names = null;
}
public boolean isEmpty()
{
return names == null;
}
public void append(String name)
{
if(names == null)
{
names = new NameNode(name,null);
}
else
{
NameNode tmp = names;
//tmp = names;
while(tmp.getNext() != null)
{
tmp = tmp.getNext();
tmp.setNext(new NameNode(name,null));
}
}
null
}
public void print()
{
NameNode current = names;
while(current != null)
{
System.out.println(current.getName());
current = current.getNext();
}
}
}
Upvotes: 1
Views: 88
Reputation: 92
You have error in your append
function of NameList
. In your code, when you append the second name, the program goes to else statement, where it evaluates false for the condition in while loop and never appends the second node. Thus your code is always able to enter only first element.
Refer the corrected append function, hopefully it would do the job.
public void append(String name)
{
if(names == null) {
names = new NameNode(name,null);
}
else{
NameNode tmp = names;
while(tmp.getNext() != null){
tmp = tmp.getNext();
}
tmp.setNext(new NameNode(name,null));
}
}
Upvotes: 1
Reputation:
Because you are passing only one name here in the constructor, and if you look at the getName()
method, you will see you only have one lastName
.
public NameNode(String lastName, NameNode toNext)
{
this.lastName = lastName;
this.next = toNext;
}
public String getName()
{
return lastName;
}
One more thing, there is only one string you have initialized which is this private String lastName;
where is the other one?
Upvotes: 0