Question

In: Computer Science

What is wrong with my add and remove method (in bold) under the SongList that it...

What is wrong with my add and remove method (in bold) under the SongList that it is creating a NullPointerException?

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 newNode = new Song(artist, title);


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

Song previous = null;
Song current = m_last;



while (current != null)
{
//System.out.println(current.getTitle() + " comparedTo " + title + ": " + (current.getTitle()).compareTo(title));
int compareToResult = (current.getTitle()).compareTo(title);

if (compareToResult < 0)
{
previous = current;
current = current.getLink();
//m_numElements++;


}

else
break;


}

if (previous == null)
{
newNode.setLink(m_last);
m_last = newNode;
m_numElements++;
}

else
{
previous.setLink(newNode);
newNode.setLink(current);
m_numElements++;
}   
}


// remove a Song associated with the given artist and title from the list,
// keeping the list sorted by *song title*.
public boolean remove(String artist, String title)
{
  
Song previous = null;
Song current = m_last;
boolean match = false;
  
while (current != null)
{
int compareToTitle = (current.getTitle()).compareToIgnoreCase(title);
int compareToArtist = (current.getArtist()).compareToIgnoreCase(artist);

if (compareToTitle < 0 && compareToArtist < 0)
{
previous = current;
current = current.getLink();
}
else if (compareToTitle == 0 && compareToArtist == 0)
{
match = true;
current = current.getLink();
  
  
if (previous == null)
m_last = current;
else
previous.setLink(current);
}
else
return match;
}
  
//return match;
return true;

}
  


  
// return a string representation of the list
// Do not make any changes to this method!
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

Your both methods are right. There is error in toString() method. It has 2 errors:

1) current node is set to next node before converting its contents to string

2) condition in do while loop is not correct. It should be while(current != null).

Correct code for toString():

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

        return listContent;
        }
    }

I tested it for follwing operations:

  SongList slist = new SongList();
  slist.add("Akon", "I wana love you");
  slist.add("Akosn", "I wana lovsd su");
  System.out.println(slist.toString());
  slist.remove("Akon", "I wana love you");
  System.out.println(slist.toString());

Output:

if it helps you do upvote as it motivates us a lot!

if you have any doubt, do share in comments section!


Related Solutions

This Array implementation allows duplicates. Add a method that searches the array and remove all the...
This Array implementation allows duplicates. Add a method that searches the array and remove all the values in the array that does not have a duplicate. void removeNoDups( ) ( 12 points) For example if array had elements 100 200 100 100 200 400 500 300, once this new method is run it should return 100 200 100 100 200 removing 400, 500 and 300 which do not have duplicate values in the array. So in short this method allows...
This Array implementation allows duplicates. Add a method that searches the array and remove all the...
This Array implementation allows duplicates. Add a method that searches the array and remove all the values in the array that does not have a duplicate. void removeNoDups( ) ( 12 points) For example if array had elements 100 200 100 100 200 400 500 300, once this new method is run it should return 100 200 100 100 200 removing 400, 500 and 300 which do not have duplicate values in the array. So in short this method allows...
I Have posted my Java code below. Fix the toString, add, and remove implementations so that...
I Have posted my Java code below. Fix the toString, add, and remove implementations so that the following test cases work. Note: I have removed all the unnecessary inherited List implementations. I have them to: throw new UnsupportedException(); For compilation, you could also add //TODO. Test (Main) List list = new SparseList<>(); list.add("0"); list.add("1"); list.add(4, "4"); will result in the following list of size 5: [0, 1, null, null, 4]. list.add(3, "Three"); will result in the following list of size...
Write a remove(E val) method for DoublyLinkedList class This method remove the first occurrence of the...
Write a remove(E val) method for DoublyLinkedList class This method remove the first occurrence of the node that contains the val. .
Write a remove(E val) method for CircularlyLinkedList class This method remove the first occurrence of the...
Write a remove(E val) method for CircularlyLinkedList class This method remove the first occurrence of the node that contains the val.
Under the MBCA, what are the steps that should be taken by a shareholder to remove...
Under the MBCA, what are the steps that should be taken by a shareholder to remove a director? Your paper should address in detail such issues as authority to act, notice, meeting and voting requirements.
Question is in bold at the end of my worksheet For the month of: November Budget...
Question is in bold at the end of my worksheet For the month of: November Budget Data Fixed Variable Actual Portion Portion* Data Depreciation $4,000         -- $4,000 Maintenance $1,800 $0.70 4,730 Inspections $2,800 0.25 3,702 Utilities $4,000 0.20 4,900 Indirect material 0.25 1,125 Overtime 2.25 ** 260 *per direct labor hour **per monthly direct labor hours in excess of 4,000 Planned direct labor hours for the month 4,500 Actual direct labor hours for the month 4,100 Static Budget Budget...
please explain the solution and what it is wrong with my conception. FOLLOW the COMMENT PLEASE...
please explain the solution and what it is wrong with my conception. FOLLOW the COMMENT PLEASE Question: Let A and B are nonempty set bounded subset of R, and let A+B be the set of all sums a+b where a belngs to A and b belongs to B Prove Sup(A+B)=Sup(A)+Sup(B) Solution: Let ε>0, a is in A and b is in B, supA<=a+(ε/2), supB<=b+(ε/2) sup(A + B) ≥ a + b ≥ sup A − ε /2 + sup B...
hi i do not know what is wrong with my python code. this is the class:...
hi i do not know what is wrong with my python code. this is the class: class Cuboid: def __init__(self, width, length, height, colour): self.__width = width self.__length = length self.__height = height self.__colour = colour self.surface_area = (2 * (width * length) + 2 * (width * height) + 2 * (length * height)) self.volume = height * length * width def get_width(self): return self.__width def get_length(self): return self.__length def get_height(self): return self.__height def get_colour(self): return self.__colour def set_width(self,...
This is a critical thinking question. I know the answers. My question is in bold below...
This is a critical thinking question. I know the answers. My question is in bold below the textbook question. Ch 13, #57PE - A deep-sea diver should breath a gas mixture that has rthe same oxygen partial pressure as at sea level, where dry air contains 20.9% oxygen and has a total pressure of 1.01x105 N/m2. When developing a strategy for solving this problem, how can the given information and the principles that govern this context lead me to what...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT