In: Computer Science
Create a linked list of Poem objects using the Poem.java file
provided. You may create Poem objects by hard coding (minimum 4),
reading from a file, or getting user input.
Print the list using ListIterator.
Here is Poem.Java:
public class Poem
{
private String title;
private String poet;
/**
* No arg constructor
*/
public Poem()
{
title = "not set";
poet = "not set";
}
/**
* @param title
* @param poet
*/
public Poem(String title, String poet)
{
super();
setTitle(title);
setPoet(poet);
}
/**
* @return the title
*/
public String getTitle()
{
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title)
{
if (title.length() > 0)
{
this.title =
title;
} else
{
this.title =
"not set";
}
}
/**
* @return the poet
*/
public String getPoet()
{
return poet;
}
/**
* @param poet the poet to set
*/
public void setPoet(String poet)
{
if (poet.length() > 0)
{
this.poet =
poet;
} else
{
this.poet = "not
set";
}
}
@Override
public String toString()
{
return "Poem [title=" + title + ",
poet=" + poet + "]";
}
}
//The code and output both have been provided in case of any doubts please do comment..
import java.util.LinkedList;
import java.util.ListIterator;
public class Poems {
public static void main(String[] args)
{
//Initializing a Linked
List of Poem Object
LinkedList<Poem>
poems = new LinkedList<Poem>();
//Adding the various
Poems to poems Linked List
poems.add(new Poem("The
Good Life", "Tracy K. Smith"));
poems.add(new Poem("How
Bright It Is", "Brian Turner"));
poems.add(new
Poem("Numbers", "Mary Cornish"));
poems.add(new Poem("The
Road Not Taken", "Robert Frost"));
poems.add(new
Poem("Daffodils", "William Wordsworth"));
poems.add(new
Poem("Sonnet 18", "William Shakespeare"));
poems.add(new Poem("A
Psalm Of Life", "Henry Wadsworth Longfellow"));
//Declaration and
initialization of list iterator to iterate over poems
ListIterator<Poem>
iterator = poems.listIterator();
System.out.println("=========================");
//It iterates until next
is not null
while
(iterator.hasNext()){
//Store current poem index in current Poem and iterate to next
poem
Poem currentPoem = iterator.next();
System.out.println("The current poem is \"" +
currentPoem.getTitle() + "\" and its author is \"" +
currentPoem.getPoet() + "\"");
}
System.out.println("=========================");
}
}