Question

In: Computer Science

What is the issue is in the add method in the SongList Class? It doesn't seem...

What is the issue is in the add method in the SongList Class? It doesn't seem to add the songs when running testing.

public class Song
{
// instance variables
private String m_artist;
private String m_title;
private Song m_link;

// constructor
public Song(String artist, String title)
{
m_artist = artist;
m_title = title;
m_link = null;
}

// getters and setters
public void setArtist(String artist)
{
m_artist = artist;
}

public String getArtist()
{
return m_artist;
}

public void setTitle(String title)
{
m_title = title;
}

public String getTitle()
{
return m_title;
}
  
public void setLink(Song link)
{
m_link = link;
}

public Song getLink()
{
return m_link;
}
}

public class SongList
{
// instance variables
private Song m_last;
private int m_numElements;

// constructor
// Do not make any changes to this method!
public SongList()
{
m_last = null;
m_numElements = 0;
}

// check whether the list is empty
// Do not make any changes to this method!
boolean isEmpty()
{
if (m_last == null)
return true;
else
return false;
}

// return the size of the list (# of Song nodes)
// Do not make any changes to this method!
public int size()
{
return m_numElements;
}

// add a new Song to the circular linked list with the given artist and
// title, keeping the list sorted by *song title*.
public void add(String artist, String title)
{
// TODO: implement this method
Song newSong = new Song(artist, title);

if(m_last == null)
{
m_last = newSong;
m_numElements++;
return;
}

Song previous = null;
Song current = m_last;

while (current != null)
{
System.out.print(" [" + current.getArtist() + " - " + current.getTitle() + "]\n");
int compareToResult = (current.getTitle()).compareToIgnoreCase(title);

  
if (compareToResult < 0)
{
previous = current;
current = current.getLink();
}
else
break;
}
System.out.print(" [" + current.getArtist() + " - " + current.getTitle() + "]\n");
if (previous == null)
{
newSong.setLink(m_last);
m_last = newSong;
m_numElements++;
}

else
{
//adds element to a non-empty list
previous.setLink(newSong);
newSong.setLink(current);

}



}

public String toString()
{   
String listContent = "";
Song current = m_last;
  
if (m_last != null)
do
{
current = current.getLink();
listContent += " [" + current.getArtist() + " - " + current.getTitle() + "]\n";

} while (current != m_last);

return listContent;
}
}

Solutions

Expert Solution

Summary:

CirculerLinkedList is a linked list whose head is connected to tail.

Circular linked list is a linked list where all nodes are connected to form a circle. There is no NULL at the end.

I fixed your SongList class, it was not storing any values because in constructor you did not initialize the instance variables properly. You must use this keyword inside your constructor. This refers to the object that is calling the method/constructor.

Another issue with your implementation was toString method, it was throwing error while printing songs.

It was failing because while condition was wrong. I fixed that as well.

But there is a problem with your implementation in circular linked there should not be any null at the end. In your implementation you are adding null to the end that is to the link of the song.

Anyways if you just want your code to work then here is your solution:

------------------------------------------Song.java----------------------------------

public class Song
{
    // instance variables
    private String m_artist;
    private String m_title;
    private Song m_link;
    Song(){
        this.m_artist = null;
        this.m_title = null;
        this.m_link = null;
    }
    // constructor
    public Song(String artist, String title)
    {
        m_artist = artist;
        m_title = title;
        m_link = null;
    }

    // getters and setters
    public void setArtist(String artist)
    {
        m_artist = artist;
    }

    public String getArtist()
    {
        return m_artist;
    }

    public void setTitle(String title)
    {
        m_title = title;
    }

    public String getTitle()
    {
        return m_title;
    }

    public void setLink(Song link)
    {
        m_link = link;
    }

    public Song getLink()
    {
        return m_link;
    }
}

----------------------------------------------SongList.java------------------------------------

public class SongList {
    // instance variables
    private Song m_last;
    private static int m_numElements;

    public SongList() {
        this.m_last = null;
        this.m_numElements = 0;
    }

    // check whether the list is empty
// Do not make any changes to this method!
    boolean isEmpty() {
        if (m_last == null)
            return true;
        else
            return false;
    }

    // return the size of the list (# of Song nodes)
// Do not make any changes to this method!
    public int size() {
        return m_numElements;
    }

    // add a new Song to the circular linked list with the given artist and
// title, keeping the list sorted by *song title*.
    public void add(String artist, String title) {
// TODO: implement this method
        Song newSong = new Song(artist, title);

        if (m_last == null) {
            m_last = newSong;
            m_numElements++;
            return;
        }

        Song previous = null;
        Song current = m_last;

        while (current != null) {
            //System.out.print(" [" + current.getArtist() + " - " + current.getTitle() + "]\n");
            int compareToResult = (current.getTitle()).compareToIgnoreCase(title);


            if (compareToResult < 0) {
                previous = current;
                current = current.getLink();
            } else
                break;
        }
        //System.out.print(" [" + current.getArtist() + " - " + current.getTitle() + "]\n");
        if (previous == null) {
            newSong.setLink(m_last);
            m_last = newSong;
            m_numElements++;
        } else {
//adds element to a non-empty list
            previous.setLink(newSong);
            newSong.setLink(current);
            m_numElements++;
        }


    }

    @Override
    public String toString() {
        String listContent = "";
        Song current = this.m_last;

        if (this.m_last != null)
            do {

                listContent += " [" + current.getArtist() + " - " + current.getTitle() + "]\n";
                current = current.getLink();

            } while (current != null);

        return listContent;
    }
}

------------------------------------------Driver.java---------------------------------------

import javax.sound.midi.Soundbank;

public class Driver {
    public static void main(String args[]) {


        // You implementation of CircularLinkedList
        SongList songList = new SongList();

        songList.add("Eminem", "Rap God");
        songList.add("Katy Perry", "Roar");

        System.out.println("Number of songs in list: ");
        System.out.println(songList.size());

        System.out.println("Songs in the list: ");
        System.out.println(songList.toString());


        // Correct implementation of CircularLinkedList. Please remove below comments to test my implementation.
        
        /*CircularLinkedList circularLinkedList = new CircularLinkedList();

        circularLinkedList.addNode("Eminem", "Rap God");
        circularLinkedList.addNode("Katy Perry", "Roar");*/
    }
}

Output:


If you want correct implentaion of Circular Linked List you can refer my code:

-----------------------------------------CircularLinkedList.java----------------------------

public class CircularLinkedList {

    // head of the circularlinked list
    private Songs head = null;

    // tail of the circularlinked list
    private Songs tail = null;


    // function to add nodes to the tail of the circular linked list
    public void addNode(String str, String title) {

        Songs newNode = new Songs(str,title);

        if (head == null) {
            head = newNode;
        } else {
            tail.nextNode = newNode;
        }

        tail = newNode;
        tail.nextNode = head;
    }



    // function to traverse the list.
    public void traverseList() {

        Songs currentNode = head;

        if (head != null) {
            do {
                // print nodes here
                currentNode = currentNode.nextNode;
            } while (currentNode != head);
        }
    }

}

class Songs {

    // instance variables
     String m_artist;
     String m_title;
    Songs nextNode;
    Songs(){
        this.m_artist = null;
        this.m_title = null;
        this.nextNode = null;
    }
    // constructor
    public Songs(String artist, String title)
    {
        m_artist = artist;
        m_title = title;
        nextNode = null;
    }

    // getters and setters
    public void setArtist(String artist)
    {
        m_artist = artist;
    }

    public String getArtist()
    {
        return m_artist;
    }

    public void setTitle(String title)
    {
        m_title = title;
    }

    public String getTitle()
    {
        return m_title;
    }

    public void setLink(Songs link)
    {
        nextNode = link;
    }

    public Songs getLink()
    {
        return nextNode;
    }

}

Please rate postive if this helped you. Thanks.


Related Solutions

Given the LinkedStack Class as covered in class add a method to the LinkedStack class called...
Given the LinkedStack Class as covered in class add a method to the LinkedStack class called PushBottom which will add a new item to the bottom of the stack. The push bottom will increase the number of items in the stack by 1
Add the method getTelephoneNeighbor to the SmartPhone class. Make this method return a version of the...
Add the method getTelephoneNeighbor to the SmartPhone class. Make this method return a version of the phone number that's incremented. Given Files: public class Demo4 { public static void main(String[] args) { SmartPhone test1 = new SmartPhone("Bret", "1234567890"); SmartPhone test2 = new SmartPhone("Alice", "8059226966", "[email protected]"); SmartPhone test3 = new SmartPhone(); SmartPhone test4 = new SmartPhone("Carlos", "8189998999", "[email protected]"); SmartPhone test5 = new SmartPhone("Dan", "8182293899", "[email protected]"); System.out.print(test1); System.out.println("Telephone neighbor: " + test1.getTeleponeNeighbor()); System.out.println(); System.out.print(test2); System.out.println("Telephone neighbor: " + test2.getTeleponeNeighbor()); System.out.println(); System.out.print(test3); System.out.println("Telephone...
Please add the following method as a part of the UnorderedList class definition: •print_list: the method...
Please add the following method as a part of the UnorderedList class definition: •print_list: the method prints the elements of the list using the same format as a Python list (square brackets and commas as separators). In the main function of the modified UnorderedList.py, please test the new method to demonstrate that it works as expected. Please leave comments in the code to show what is done UnorderList.py file # Implementation of an Unordered List ADT as a linked list....
Hypothetical -- Your sister or brother is in an unhealthy relationship but doesn't seem to see...
Hypothetical -- Your sister or brother is in an unhealthy relationship but doesn't seem to see the warning signs. 1a.How could you alert her/him to the potential dangers? 1b.How can toxic relationship affect one's health?
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a...
Modify Example 5.1 to add a ReadAccount method to the BankAccount class that will return a BankAccountconstructed from data input from the keyboard. Override ReadAccount in SavingsAccount to return an account that refers to a SavingsAccount that you construct, again initializing it with data from the keyboard. Similarly, implement ReadAccount in the CheckingAccount class. Use the following code to test your work. public static void testCode()         {             SavingsAccount savings = new SavingsAccount(100.00, 3.5);             SavingsAccount s = (SavingsAccount)savings.ReadAccount();...
Add a method to OurQueue class that dequeues the Nth item on a queue and returns...
Add a method to OurQueue class that dequeues the Nth item on a queue and returns it. It must remove the Nth item from the Queue but leave the rest of the queue. Test it with the following code: Console.WriteLine("Testing DequeueNth"); OurQueue<string> ourQ = new OurQueue<string>(12); // Empty Q try { ourQ.DequeueNth(0); Console.WriteLine("\a Error on empty list"); } catch { Console.WriteLine("Empty Queue worked"); } for (int i = 0; i < 9; ++i) ourQ.Enqueue("a" + i); for (int i =...
public class AddValueToArray { // You must define the addValueTo method, which will add // a...
public class AddValueToArray { // You must define the addValueTo method, which will add // a given value to each element of the given array. // // TODO - define your code below this comment // // DO NOT MODIFY main! public static void main(String[] args) { int[] array = new int[]{3, 8, 6, 4}; int valueToAdd = Integer.parseInt(args[0]); addValueTo(valueToAdd, array); for (int index = 0; index < array.length; index++) { System.out.println(array[index]); } } }
Add a public method called CountChildren to the OurPriorityQueue class that receives a priority value and...
Add a public method called CountChildren to the OurPriorityQueue class that receives a priority value and returns the number of children nodes below the node with the priority value. It must call a private recursive method that does the actual counting of children nodes. The recursive private method must count and return the number of nodes within a subtree where the subtree’s “root” node has a Value that equals the value passed into the method. Do not include the parent...
Problem: Add a condition to the deposit method of the BankAccount class, restricting deposits to $100,000...
Problem: Add a condition to the deposit method of the BankAccount class, restricting deposits to $100,000 (the insurance limit of the U.S. government). The method should block until sufficient money has been withdrawn by another thread. Test your program with a large number of deposit threads. (All other classes are provided below) Bank Account.java (This class is the one that needs to be modified) /** A bank account has a balance that can be changed by deposits and withdrawals. */...
In the program the "case: 'C'" doesn't seem to function correctly, We were told to write...
In the program the "case: 'C'" doesn't seem to function correctly, We were told to write a book tracking program, and it takes inputs and once all the book info such as ISBN, date, author, course number, etc are put in then input, then we can print them out, by using the print functions that are defined in the program. Example: the formats are as follows, when defining the book: "B-ISBN-TITLE" So then in the terminal once the code compiles...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT