NSaid
NSaid

Reputation: 751

How can I display objects from linked list JAVA

I would like some help in displaying objects that I have added to a linked list. Now the display function works when I return data at a specific position in the list. However I can not print any information from the whole list. I tried using a for loop and calling my function that allowed me to print the information at a specific position but all that did was print the last element. I have attached my code below:

WordList.java

// Returns the data at the specified position in the list.
protected Word get(int pos){
    if (head == null) throw new IndexOutOfBoundsException();
    Node<Word> temp = head;
    for (int k = 0; k < pos; k++) temp = temp.getNext();
        if( temp == null) throw new IndexOutOfBoundsException();
        return temp.getData();
}

// Displays the word in the list
protected void display(){
    Node<Word> temp = head;
    for (int k = 0; k < getListSize(); k++)
        System.out.println(k);
        /*if(temp == null) throw new IndexOutOfBoundsException();*/
        temp.getData();
        temp = temp.getNext();
}

Upvotes: 0

Views: 1189

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234795

You're missing brackets around the body of your for loop:

protected void display(){
    Node<Word> temp = head;
    for (int k = 0; k < getListSize(); k++) {
        System.out.println(k);
        Word word = temp.getData();
        /* print word */
        temp = temp.getNext();
    }
}

Upvotes: 2

Related Questions