Question

In: Computer Science

Objectives: Define the new class type: Queue using a singly linked list. Define the new class...

Objectives:

  • Define the new class type: Queue using a singly linked list.
  • Define the new class type: Jukebox which creates three objects of type Queue class.
  • Practice enqueue-ing and dequeue-ing elements from the top of your singly linked list Queue class.
  • Test the implementation of the class: MyTunes.

The class files are here: https://drive.google.com/file/d/1yCCQeZCS-uLoL_CK0Et9dX-KCaokXQxR/view?usp=sharing

class MyTunes

Creates an object of type MyTunes class that partially simulate the digital jukebox TouchTunes, using a queue which holds playlist. Tests the implementation of your Queue and Jukebox classes.

From main your program:

  • Starts by creating an object of type MyTunes which initializes three playlists favoritesPL, loungePL, and roadTrip by reading the input file "tunes.txt" which contains one type of line entry:
    • playlist songTitle
      Indicates that the user wants to add a SongEntry object with a specific songTitle to the playlist .
  • Then it prompts the user for total songs they want to play.
  • It simulates playing one song at a time from each playlist until either:
    • we've played the total requested number of songs;
    • or all playlists are empty.
  • Reminder: in a queue data structure we process items in FIFO (First-In-First-Out) order.

class Jukebox

Define the class Jukebox to manage three objects of type Queue<SongEntry>. The class Jukebox manages three objects of type Queue. An instance of the class may read a file which includes the user's requests for a the name of a song to be added to a specific playlist. It will then add songs to the three playlists "favorites", "lounge", and "road trip" accordingly.

Attributes:

  • A variable called favoritePL of type Queue<SongEntry> which simulates the playlist referred to as "favorites" in the input file.
  • A variable called roadTripPL of type Queue<SongEntry> which simulates the playlist referred to as "road trip" in the input file.
  • A variable called loungePL​ of type Queue<SongEntry> which simulates the playlist referred to as "lounge" in the input file.

Methods:

  • A method called fillPlaylists()  reads the test file and then adds songs to one of the three queues. For example, if the file contains line:

    favorites,title 
    

    Then the first song found that equals the title will be placed in the favorites playlist.

  • Accessor methods getFavoritePL(), getRoadTripPL() and getLoungePL() for each of the three queue structures favoritePL, roadTripPL and loungePL respectively.

class Queue<Type>

Define the parameterized class Queue which implements Iterable. Objects of type Queue manage items in a singly linked list where we can enqueue() items to the end and dequeue() items from the front of the queue.

Attributes:

  • A variable called name of type String for the name of this instance. We we will use this for testing and debugging purposes.
  • A variable called head, which points to the front of the queue.
  • A variable called tail​, which points to the end of the queue.

Methods:

  • A constructor that takes in a user assigned name and initializes the class attributes.
  • A method called enqueue() which takes a generic item as the argument and adds the item to the end of the queue.
  • A method called dequeue() which receives no arguments and removes the item from the front of the queue. This method should return the generic item dequeue-ed. This method should throw an NoSuchElementException if the queue is empty.
  • A method called peek which looks at the least recently added item of the queue and returns an object of the generic type for the data seen at the front of the queue. The item should not be removed from the front of the queue.
    NOTE: If the queue is empty, returns null.
  • The methods isEmpty(), size() and toString() method.

Input File Format:

The format of the "tunes.txt" input file is:

favorites,Shadows - Original
road trip,Tom's Diner
favorites,Take Me Away
road trip,Here With Me
lounge,Nuvole Bianche
lounge,Luka
favorites,Stoned
road trip,Get Happy
favorites,We Belong
road trip,Let's Dance
road trip,Oh What a Feeling
favorites,Stairway To The Stars
road trip,Separate Ways (Worlds Apart)
road trip,Road Home
lounge,Traffic

Output of example 1 showing non-empty queues:

Welcome! We have over 59600 in FoothillTunes store! 
Total number of songs in playlists: 16

Songs in each playlist:

favorites:
[Shadows - Original, 0:0:25, Blue Oyster Cult, classic pop and rock;
Take Me Away, 0:4:32, Blue Oyster Cult, classic pop and rock;
Stoned, 0:11:47, Dido, classic pop and rock;
We Belong, 0:3:43, Pat Benatar, classic pop and rock;
Stairway To The Stars, 0:3:46, Blue Oyster Cult, classic pop and rock]

lounge:
[Solo, 0:4:41, Working Week, classic pop and rock;
Nuvole Bianche, 0:5:58, Ludovico Einaudi, classical;
Luka, 0:3:52, Suzanne Vega, classic pop and rock;
Traffic, 0:4:5, Dawn Landes, classic pop and rock]

road trip:
[Tom's Diner, 0:2:40, Suzanne Vega, classic pop and rock;
Here With Me, 0:4:41, Dido, classic pop and rock;
Get Happy, 0:6:36, Jean Knight, classic pop and rock;
Let's Dance, 0:2:45, Jake Shimabukuro, folk;
Oh What a Feeling, 0:3:42, Gregory Isaac, classic pop and rock;
Separate Ways (Worlds Apart), 0:5:25, Journey, classic pop and rock;
Road Home, 0:5:8, The String Cheese Incident, folk]

Enter your the number of songs you would like to play:
7

Playing 7 number of songs...
Playing song title "Shadows - Original"
Playing song title "Solo"
Playing song title "Tom's Diner"
Playing song title "Take Me Away"
Playing song title "Nuvole Bianche"
Playing song title "Here With Me"
Playing song title "Stoned"

Checking the size of each playlist:
Playlist "favorites" is 2 song(s) remaining.
Playlist "lounge" is 2 song(s) remaining.
Playlist "road trip" is 5 song(s) remaining.

Songs in each list:

favorites:
[We Belong, 0:3:43, Pat Benatar, classic pop and rock;
Stairway To The Stars, 0:3:46, Blue Oyster Cult, classic pop and rock]

lounge:
[Luka, 0:3:52, Suzanne Vega, classic pop and rock;
Traffic, 0:4:5, Dawn Landes, classic pop and rock]

road trip:
[Get Happy, 0:6:36, Jean Knight, classic pop and rock;
Let's Dance, 0:2:45, Jake Shimabukuro, folk;
Oh What a Feeling, 0:3:42, Gregory Isaac, classic pop and rock;
Separate Ways (Worlds Apart), 0:5:25, Journey, classic pop and rock;
Road Home, 0:5:8, The String Cheese Incident, folk]

Done with MyTunes.

Output of example 2 with input test file "tunes_truncated.txt" where some queues are empty when calling dequeue() method of class Queue:

Welcome! We have over 59600 in FoothillTunes store! 
Total number of songs in playlists: 3

Songs in each playlist:

favorites:
[Shadows - Original, 0:0:25, Blue Oyster Cult, classic pop and rock]

lounge:
[Solo, 0:4:41, Working Week, classic pop and rock]

road trip:
[Tom's Diner, 0:2:40, Suzanne Vega, classic pop and rock]

Enter your the number of songs you would like to play:
4

Playing 4 number of songs...
Playing song title "Shadows - Original"
Playing song title "Solo"
Playing song title "Tom's Diner"

Checking the size of each playlist:
Playlist "favorites" has *no* songs remaining.
Playlist "lounge" has *no* songs remaining.
Playlist "road trip" has *no* songs remaining.

Songs in each list:

favorites:
[ ]

lounge:
[ ]

road trip:
[ ]

Done with MyTunes.

Solutions

Expert Solution

Answer: See the code below:

1. Queue class: Queue.java

------------------------------------------

package mytunesdemo;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
* Queue class
* @param <T>
*
*/
public class Queue<T> implements Iterable<T>{
  
   //node in the queue
   class Node
   {
       T item;
       Node next;
   }
  
   private String name; //name of instance
   private Node head; //front of the queue
   private Node tail; //end of the queue
   private int numItems; //number of items in queue  
  
   /**
   * @param name
   */
   public Queue(String name) {
       this.name = name;
       this.head = null;
       this.tail = null;      
       this.numItems = 0;
   }
  
   /**
   *
   * @return true if queue is empty.
   */
   public boolean isEmpty()
   {
       return (size() == 0);
   }
   /**
   * enqueues an item to the end of the queue
   * @param item
   */
   public void enqueue(T item)
   {
       Node n = new Node();
       n.item = item;
       n.next = null;
       if(isEmpty())
       {  
           head = n;
           tail = n;
       }
       else
       {
           tail.next = n;
           tail = n;
       }
       numItems++;
   }

   /**
   * dequeues an item from the front of list
   * @return
   */
   public Node dequeue()
   {
       Node n = null;
       if (isEmpty())
           throw new NoSuchElementException();
       else
       {
           n = head;
           head = head.next;
       }
       numItems--;
       return n;      
   }

   /**
   *
   * @return most recently added element to the queue.
   */
   public Node peek()
   {
       if(isEmpty())
           return null;
       else
           return head;
   }
  
   /**
   *
   * @return size of the queue.
   */
   public int size()
   {
       return numItems;
   }  
      
   /* (non-Javadoc)
   * @see java.lang.Object#toString()
   */
   @Override
   public String toString() {
       return "Queue [" + (name != null ? "name=" + name + ", " : "") + (head != null ? "head=" + head + ", " : "")
               + (tail != null ? "tail=" + tail + ", " : "") + "numItems=" + numItems + "]";
   }

   @Override
   public Iterator<T> iterator() {
       // TODO Auto-generated method stub
       return null;
   }  
}

--------------------------------------

2. JukeBox class: Jukebox.java

------------------------------------------------

package mytunesdemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
* JukeBox class
*
*/
public class JukeBox {
   private Queue<SongEntry> fovoritePL; //fovorite playlist
   private Queue<SongEntry> roadTripPL; //road trip playlist
   private Queue<SongEntry> loungePL; //lounge playlist
  
   /**
   * Default constructor
   */
   public JukeBox() {
       fovoritePL = new Queue<SongEntry>("favorites");
       roadTripPL = new Queue<SongEntry>("road trip");
       loungePL = new Queue<SongEntry>("lounge");
   }

   /**
   * fills play lists from the file specified
   */
   public void fillPlayLists(String filename)
   {
       try {
           File inputFile = new File(filename);
           BufferedReader reader = new BufferedReader(new FileReader(inputFile));
           String line;
           while((line=reader.readLine())!=null)
           {
               String[] tokens = line.split(",");
               String listType = tokens[0];
               String songTitle = tokens[1];
               SongEntry songEntry = new SongEntry(songTitle);
               if(listType.equals("fovorites"))
               {
                   fovoritePL.enqueue(songEntry);
               }
               else if(listType.equals("road trip"))
               {
                   roadTripPL.enqueue(songEntry);
               }
               else if(listType.equals("lounge"))
               {
                   loungePL.enqueue(songEntry);
               }
           }
           reader.close();
       } catch (FileNotFoundException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
   }

   /**
   * @return the fovoritePL
   */
   public Queue<SongEntry> getFovoritePL() {
       return fovoritePL;
   }

   /**
   * @return the roadTripPL
   */
   public Queue<SongEntry> getRoadTripPL() {
       return roadTripPL;
   }

   /**
   * @return the loungePL
   */
   public Queue<SongEntry> getLoungePL() {
       return loungePL;
   }  
}
--------------------------------------------


Related Solutions

In C++, Implement the queue ADT with a singly linked list
In C++, Implement the queue ADT with a singly linked list
Write a template class that implements an extended queue (use singly Linked List) in c++ please...
Write a template class that implements an extended queue (use singly Linked List) in c++ please create 3 classes please create 3 classes please create 3 classes please create 3 classes please create 3 classes Ex: ExtendedQueue int_queue; ExtendedQueue double_queue; ExtendedQueue char_queue; –Write a program to test this template class. you have to use inheritance so you will create 3 classes : so you will create 3 classes : so you will create 3 classes : so you will create...
Using the singly linked list code as a base, create a class that implements a doubly...
Using the singly linked list code as a base, create a class that implements a doubly linked list. A doubly linked list has a Previous link so you can move backwards in the list. Be sure the class is a template class so the user can create a list with any data type. Be sure to test all the member functions in your test program. c++
Write a code to implement a python queue class using a linked list. use these operations...
Write a code to implement a python queue class using a linked list. use these operations isEmpty • enqueue. • dequeue    • size Time and compare the performances of the operations ( this is optional but I would appreciate it)
Define empty methods in Queue class using LinkedList class in Java ------------------------------------------------------------------------------- //Queue class public class...
Define empty methods in Queue class using LinkedList class in Java ------------------------------------------------------------------------------- //Queue class public class Queue{ public Queue(){ // use the linked list } public void enqueue(int item){ // add item to end of queue } public int dequeue(){ // remove & return item from the front of the queue } public int peek(){ // return item from front of queue without removing it } public boolean isEmpty(){ // return true if the Queue is empty, otherwise false }...
class SLinkedList: """Singly linked list with access to front and end, and with stored size. """...
class SLinkedList: """Singly linked list with access to front and end, and with stored size. """ #-------------------------- nested _Node class -------------------------- class _Node: __slots__ = '_element', '_next' # streamline memory usage def __init__(self, element, next): self._element = element self._next = next #------------------------------- queue methods ------------------------------- def __init__(self): """Create an empty list.""" self._head = None self._tail = None self._size = 0 def __len__(self): """Return the number of elements in the list.""" return self._size def isEmpty(self): """Return True if the list is...
Python: Solve following problems using Linked List Data Structure 2. Create a Queue class. In the...
Python: Solve following problems using Linked List Data Structure 2. Create a Queue class. In the queue class create enqueue, dequeue, first, empty, len and resize methods. The class should support circular queue and have the ability to resize the queue.
Using the linked list abstract data type “Queue ADT”, write a menu dirven user interfece to...
Using the linked list abstract data type “Queue ADT”, write a menu dirven user interfece to teach each of the operations in the ADT. Any errors discovered during the processing should be printed as a part of the test result. Please Use C++ language.
I was supposed to conver a singly linked list to a doubly linked list and everytime...
I was supposed to conver a singly linked list to a doubly linked list and everytime I run my program the output prints a bunch of random numbers constantly until I close the console. Here is the code. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> struct node { int data; struct node *next; struct node *prev; }; //this always points to first link struct node *head = NULL; //this always points to last link struct node *tail = NULL;...
Solve this Write a C++ class that implements a stack using a linked list. The type...
Solve this Write a C++ class that implements a stack using a linked list. The type of data contained in the stack should be double. The maximum size of the stack is 30. Implement the following methods: . · Constructor and destructor; // 5 pts · void push (double value); // pushes an element with the value into the stack. 5 pts. · double pop (); // pops an element from the stack and returns its value. 5 pts. ·...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT