Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Need Assistance with a Simple Queue

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Need Assistance with a Simple Queue

    Hi, I've been given an assignment to develop a class that deals with a simple shuffling array type queue with the following important methods:

    enqueue: adds an object to the rear of the queue.
    dequeue: removes and returns an object from the front of the queue.
    peek: returns the object at the front of the queue without removing it.

    I've got most of it implemented and working but I'm having trouble getting the dequeue method working according to the test code I've been given (which I will include below).

    Here is my code:

    public class DSAQueue
    {
    	public static final int DEFAULT_CAPACITY = 100;
     
    	private Object[] queue;
    	private int count;
    	private int front;
    	private int rear;
     
    	public DSAQueue ()
    	{
    		queue = new Object[DEFAULT_CAPACITY];
    		count = 0;
    		front = 0;
    		rear = 0;
    	}
    	public DSAQueue (int maxCapacity)
    	{
    		queue = new Object[maxCapacity];
    		count = 0;
    		front = 0;
    		rear = 0;
    	}
    	public int getCount()
    	{
    		return count;
    	}
    	public boolean isEmpty ()
    	{
    		return (count == 0);
    	}
    	public boolean isFull ()
    	{
    		return (count == queue.length);
    	}
    	public void enqueue (Object value)
    	{
    		if (isFull())
    		{
    			throw new IllegalStateException("Object array is full");
    		}
    		else
    		{
    			//System.out.println("rear is: " + rear);
    			//System.out.println("front is: " + front);
    			if(rear == 0)
    			{
    				queue[rear] = value;
    				rear += 1;
    				count += 1;
    			}
    			else
    			{
    				queue[rear += 1] = value;
    				count += 1;
    			}
    		}
    	}
    	public Object dequeue ()
    	{
    		Object frontVal;
     
    		if (isEmpty())
    		{
    			throw new IllegalStateException("Object array is empty");
    		}
    		else
    		{				
    			frontVal = queue[front];
    			front += 1;
    			count -= 1;
    		}
    		return frontVal;
    	}
    	public Object peek ()
    	{
    		Object frontVal;
     
    		if (isEmpty())
    		{
    			throw new IllegalStateException("Object array is empty");
    		}
     
    		frontVal = queue[front];
     
    		return frontVal;
    	}
    }

    And here is the test code:

    import java.io.*;
    import io.*;
     
     
    public class UnitTestDSAQueueArray
    {	
    	public static void main(String args[])
    	{
            int ii;
            int iNumPassed;
            int iNumTests;
            DSAQueue q;
            Ore ironOre;
            OrePile orePile;
     
            // Assume Ore works...
            ironOre = new Ore(Ore.ORETYPE_IRON, "t");
            q = new DSAQueue();
            iNumTests = 0;
            iNumPassed = 0;
     
            System.out.println("\n");
            System.out.println("Testing Normal Conditions - Constructor");
            System.out.println("=======================================");
     
            try {
                iNumTests++;
                System.out.print("Testing (count=0): ");
                if (q.getCount() != 0)
                    throw new IllegalArgumentException("Count must equal zero.");
                System.out.println("passed");
                iNumPassed++;
            } catch(Exception e) { System.out.println("FAILED"); }
     
            try {
                iNumTests++;
                System.out.print("Testing dequeue(): ");
                if (q.dequeue() != null)
                    System.out.println("FAILED");
            } catch(Exception e) { iNumPassed++; System.out.println("passed"); }
     
            System.out.println("\n");
            System.out.println("Testing Normal Conditions - Methods");
            System.out.println("===================================");
     
            try {
                iNumTests++;
                System.out.println("Testing enqueue(): ");
     
                for (ii = 1; ii <= 10; ii++)
                {
                    // Create queue of iron ore piles.
                    q.enqueue(new OrePile(ironOre, ii, 50));
                    System.out.println("Front of queue: " + ii);
                }
                iNumPassed++;
                System.out.println("Testing enqueue(): passed");
            } catch (Exception e) { System.out.println("FAILED"); }
     
            try {
                iNumTests++;
                System.out.print("Testing peek(): ");
                orePile = (OrePile)q.peek();
                if (orePile.getWeight() != 1)
                    throw new IllegalStateException("Not looking at first ore pile.");
                iNumPassed++;
                System.out.println("passed");
            } catch (Exception e) { System.out.println("FAILED"); }
     
            try {
                iNumTests++;
                System.out.println("Testing dequeue(): ");
     
                for (ii = 1; ii <= 10; ii++)
                {
                    orePile = (OrePile)q.dequeue();
     
                    // Verify that queue was OK.
                    if ((int)orePile.getWeight() != ii)
                    {
                        throw new IllegalStateException("Queue testing failed at index " + ii);
                    }
     
                    System.out.println("Front of queue: " + ii);
                }
                iNumPassed++;
                System.out.println("Testing dequeue(): passed");
            } catch (Exception e) { System.out.println("FAILED"); }
     
            try {
                iNumTests++;
                System.out.print("Testing isEmpty(): ");
                if (q.isEmpty() == false)
                    throw new IllegalStateException("Queue is empty.");
                iNumPassed++;
                System.out.println("passed");
            } catch (Exception e) { System.out.println("FAILED"); }
     
            try {
                iNumTests++;
                System.out.print("Testing isFull(): ");
                for (ii = 1; ii <= 100; ii++)
                    q.enqueue(new OrePile(ironOre, ii, 50));
                if (q.isFull() == false)
                    throw new IllegalStateException("Queue is full.");
                System.out.println("passed");
                iNumPassed++;
            } catch (Exception e) { System.out.println("FAILED"); }
     
            System.out.println("\n");
            System.out.println("Testing Error Conditions - Methods");
            System.out.println("==================================");
     
            try {
                iNumTests++;
                System.out.print("Testing enqueue() for full queue: ");
                // Enqueue another item onto full queue (see previous test) - should fail.
                q.enqueue(new OrePile(ironOre, 101, 50));             
                System.out.println("FAILED");
            } catch(Exception e) { iNumPassed++; System.out.println("passed"); }
     
            try {
                iNumTests++;
                System.out.print("Testing dequeue() for empty queue: ");
                // First dequeue all items from queue.
                for (ii = 1; ii <= 100; ii++)
                    orePile = (OrePile)q.dequeue();
                // Now try to dequeue a non-existing item.
                if (q.dequeue() != null)
                    System.out.println("FAILED");
            } catch(Exception e) { iNumPassed++; System.out.println("passed"); }
     
            try {
                iNumTests++;
                System.out.print("Testing peek() for empty queue: ");
                orePile = (OrePile)q.peek();
                System.out.println("FAILED");
            } catch (Exception e) { iNumPassed++; System.out.println("passed"); }
     
            // Ensure that queue coded to use Object rather than OrePile.
            try {
                iNumTests++;
                System.out.print("Testing Object queue: ");
                q = new DSAQueue();
                for (ii = 1; ii <= 10; ii++)
                    q.enqueue("string test");
                System.out.println("passed");
                iNumPassed++;
            } catch (Exception e) { System.out.println("FAILED"); }
     
            System.out.println("\n");
            System.out.println("Number PASSED: " + iNumPassed + "/" + iNumTests + " (" + (int)(100.0*(double)iNumPassed/(double)iNumTests) + "%)");
        }
    }

    Any help you can provide here would be much appreciated, thanks!


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Need Assistance with a Simple Queue

    What does the code do? What exactly do you expect it to do? Where exactly (what line number) does the execution of the program differ from what you expect?

    I recommend stepping through this with a debugger, or at least adding some print statements, to figure out what's going on.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Junior Member
    Join Date
    Sep 2013
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Need Assistance with a Simple Queue

    The code is basically creating and modifying a queue of objects, it is to be used by other classes in a larger project but that is out of scope for now. The issue I'm having now is with the method dequeue(), which starts on line 59. I believe the issue is when the for loop in the test code (line 74) is run, it manages to dequeue the first object in the queue but then it fails when attempting the next one. I've run through it several times with print statements but I can't pinpoint exactly where it fails.

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Need Assistance with a Simple Queue

    Especially when asking for help, you should provide the simplest example possible to demonstrate the problem, something like I've posted below. In fact, creating a simple example for yourself might/should help you discover the problem by removing the other variables that could be contributing to, hiding, or additional problems themselves. Try running what I've posted and see if you gain insight.
    public class TestClass
    {   
        static DSAQueue q;
     
        public static void main(String args[])
        {
            q = new DSAQueue();
     
            System.out.println("Testing enqueue(): ");
     
            for (int i = 1; i <= 10; i++)
            {
                // Create queue of iron ore piles.
                q.enqueue( "number" + i);
                System.out.println("Front of queue: " + i);
            }
     
            System.out.println("\nTesting dequeue()");
     
            for (int i = 1; i <= 10; i++)
            {
                System.out.println( (String)q.dequeue() );
            }
        }
    }
     
    class DSAQueue
    {
        public static final int DEFAULT_CAPACITY = 100;
     
        private Object[] queue;
        private int count;
        private int front;
        private int rear;
     
        public DSAQueue ()
        {
            queue = new Object[DEFAULT_CAPACITY];
            count = 0;
            front = 0;
            rear = 0;
        }
        public DSAQueue (int maxCapacity)
        {
            queue = new Object[maxCapacity];
            count = 0;
            front = 0;
            rear = 0;
        }
        public int getCount()
        {
            return count;
        }
        public boolean isEmpty ()
        {
            return (count == 0);
        }
        public boolean isFull ()
        {
            return (count == queue.length);
        }
        public void enqueue (Object value)
        {
            if (isFull())
            {
                throw new IllegalStateException("Object array is full");
            }
            else
            {
                //System.out.println("rear is: " + rear);
                //System.out.println("front is: " + front);
                if(rear == 0)
                {
                    queue[rear] = value;
                    rear += 1;
                    count += 1;
                }
                else
                {
                    queue[rear += 1] = value;
                    count += 1;
                }
            }
        }
        public Object dequeue ()
        {
            Object frontVal;
     
            if (isEmpty())
            {
                throw new IllegalStateException("Object array is empty");
            }
            else
            {               
                frontVal = queue[front];
                front += 1;
                count -= 1;
            }
            return frontVal;
        }
        public Object peek ()
        {
            Object frontVal;
     
            if (isEmpty())
            {
                throw new IllegalStateException("Object array is empty");
            }
     
            frontVal = queue[front];
     
            return frontVal;
        }
    }

  5. The Following User Says Thank You to GregBrannon For This Useful Post:

    Magikjak (September 9th, 2013)

Similar Threads

  1. Queue Simulation
    By spiderd in forum What's Wrong With My Code?
    Replies: 78
    Last Post: April 5th, 2013, 04:33 PM
  2. Priority Queue help
    By BuhRock in forum What's Wrong With My Code?
    Replies: 7
    Last Post: November 3rd, 2011, 06:37 PM
  3. queue question
    By Herah in forum Object Oriented Programming
    Replies: 2
    Last Post: November 3rd, 2011, 06:04 AM
  4. Question about blocking queue
    By Kerr in forum Threads
    Replies: 2
    Last Post: April 8th, 2011, 04:59 AM
  5. Priority Queue using comparable
    By jkalm in forum Collections and Generics
    Replies: 6
    Last Post: December 5th, 2010, 10:02 PM

Tags for this Thread