Welcome to Dream.In.Code
Become a Java Expert!

Join 149,506 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,327 people online right now. Registration is fast and FREE... Join Now!




Problems enqueing/dequeing the date

 
Reply to this topicStart new topic

Problems enqueing/dequeing the date

cobrec
12 Jul, 2007 - 04:37 AM
Post #1

New D.I.C Head
*

Joined: 10 Mar, 2007
Posts: 29


My Contributions
Attached File  Date.zip ( 6.69k ) Number of downloads: 26


Ok,

Here is last week's assignment... Which is late. i have asked my fellow classmates for help, but unfortunately none of them were able to help me. here are the problems with the attached QueofDates.java file:

1. When you enqueue the date it enques the same date over and over again.

2. I could not figure out at all how to dequeue the dates.

Any help you can provide would be greatly appreciated. I will also post the source code here.


Thanks,

Cobrec

CODE

//QueofDates.java
//enqueue and dequeue strings to/from a queue.
//the queue can be bounded or unbounded in size.

//LinkedList is used as the queue.
//Its addLast() is the enqueue operation
// (end of the LinkedList is the tail of the queue).
//Its removeFirst()is the dequeue operation
// (front of the LinkedList is the head of the queue).

import java.util.*;
import javax.swing.*;

public class QueofDates {

public static void main(String[] args) {
String input, userCommand, headOfQueue, newTailOfQueue;
char op;

int queueMaxSize=-1; //fakeout compiler
boolean isQueueBounded;

ArrayList myDatesList = new ArrayList();

LinkedList myQueue = new LinkedList(); //***create empty queue


input = JOptionPane.showInputDialog("Enter (maximum) number of random dates");
queueMaxSize = Integer.parseInt( input );

//**array list of random Dates
for (int i=1; i<=queueMaxSize; i++) {
myDatesList.add(generateRandomDate()); //**pseudo data...
}

//iterate over them
Iterator it=myDatesList.iterator();
System.out.println();
System.out.println("Here are your dates: ");

Date thisDate;
while (it.hasNext()) {
//reference to the Date in the list.
//***next() returns Object, must cast to Date:
thisDate = (Date)(it.next());
//thisDate = (it.next()); //**failure to cast would be compile error
System.out.print(thisDate);
//***access a method of the Date object:
System.out.println(" Month is: " + thisDate.getMonth());
}
System.out.println();


//what does sorting do to Dates?
//Collections.sort(myDatesList); //***would be runtime error.
//***there is no "natural ordering" for user-defined classes.
//***must specify how dates are compared with a Comparator.
//DateComparator is defined in another file.
Collections.sort(myDatesList,new DateComparator()); //***

it = myDatesList.iterator();
System.out.println("Here are your dates in sorted order: ");

while (it.hasNext()) {

System.out.println(it.next());
    
//while (it.hasNext()) {
    //thisDate = (Date)(it.next());          
    //System.out.print(thisDate);
    //System.out.println("     Month is: " + thisDate.getMonth());

}
System.out.println();

printQueue( myQueue ); //show queue at every operation

while (it.hasNext()) {
    thisDate = (Date)(it.next());          
    System.out.print(thisDate);
    System.out.println("     Month is: " + thisDate.getMonth());
}
System.out.println();
                        
printQueue( myQueue ); //show queue at every operation

do {
    userCommand = JOptionPane.showInputDialog( "Enqueue or Dequeue or Quit" );
     op =  userCommand.toUpperCase().charAt(0);
    if (op == 'E') {
          
  if (myQueue.size()==queueMaxSize)  //***
      System.out.println("  Queue is full!  Can not enqueue.");
  else {
  
   it = myDatesList.iterator();
   thisDate = (Date)(it.next());
   myQueue.addLast(thisDate); //***** enqueue
    
  }
     }
     else if (op == 'D') {
  if (!myQueue.isEmpty()) {   //***** check queue (LinkedList) is not empty
      //***** dequeue Obect cast to needed type:
      //headOfQueue = (String) myQueue.removeFirst();
      thisDate = (Date)(it.next());
      //myQueue.removeFirst(thisDate);   //***** dequeue
      //it = myQueue.iterator();
      
   //System.out.println("Dequeued: " + headOfQueue);
    System.out.println("Dequeued: "); }
    
else
     System.out.println("  Queue is empty!  Nothing to dequeue.");
    }
   printQueue( myQueue );  //show queue at every operation


} while (op != 'Q');

System.exit(0);
}

static void printQueue( LinkedList q) {
System.out.print("Queue is: ");
//don't normally iterate over a queue. here for illustration purposes.
Iterator items = q.iterator();
while (items.hasNext())
System.out.print(items.next()+" ");
System.out.println();
}
//generate a random Date. Note this is not a method of the Date class.
//it creates and returns a Date object.
public static Date generateRandomDate() {
int year, month, day=0;

year = (int)(Math.random()*20+1995); // +/- 10 years from 2005
month = (int)(Math.random()*12+1);
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
day = (int)(Math.random()*31+1);
break;
case 4:
case 6:
case 9:
case 11:
day = (int)(Math.random()*30+1);
break;
case 2:
if (year%4==0 && year%100!=0 || year%400==0) //leap year test
day = (int)(Math.random()*29+1);
else
day = (int)(Math.random()*28+1);
break;
}
//instantiate a Date object using the 3-arg constructor,
//then return the object to caller.
return new Date(month,day,year);

}
}

User is offlineProfile CardPM
+Quote Post

Amadeus
RE: Problems Enqueing/dequeing The Date
12 Jul, 2007 - 06:42 AM
Post #2

g++ -o drink whiskey.cpp
Group Icon

Joined: 12 Jul, 2002
Posts: 12,349



Thanked: 51 times
Dream Kudos: 25
My Contributions
Have you checked to make sure that the random dates being created are indeed different?
User is online!Profile CardPM
+Quote Post

cobrec
RE: Problems Enqueing/dequeing The Date
12 Jul, 2007 - 08:48 AM
Post #3

New D.I.C Head
*

Joined: 10 Mar, 2007
Posts: 29


My Contributions
QUOTE(Amadeus @ 12 Jul, 2007 - 07:42 AM) *

Have you checked to make sure that the random dates being created are indeed different?



Yes, the random dates are being printed, just not enqueued.... I have tried to find examples that fit into my situation and have found none... and unfortunately my classmates seem as bewildered as I am...what I need is good solid code to fix these problems, so that I can share this info with my fellow classmates. I have included all the necessary files in the zip file... all you need to do is compile QueofDates.java to see what I am refering to.

Thanks,

John
User is offlineProfile CardPM
+Quote Post

Programmist
RE: Problems Enqueing/dequeing The Date
12 Jul, 2007 - 10:17 AM
Post #4

Four-letter word
Group Icon

Joined: 2 Jan, 2006
Posts: 1,250



Thanked: 11 times
Dream Kudos: 100
Expert In: Java

My Contributions
Look at your do-while loop in your main method. You have it = myDatesList.iterator();. So, every time you iterate through that loop that line creates a new Iterator. Your code would work except for this one line. I wonder...should you remove it? Move it somewhere else? Hmmm. smile.gif
User is offlineProfile CardPM
+Quote Post

cobrec
RE: Problems Enqueing/dequeing The Date
12 Jul, 2007 - 09:29 PM
Post #5

New D.I.C Head
*

Joined: 10 Mar, 2007
Posts: 29


My Contributions
QUOTE(alcdotcom @ 12 Jul, 2007 - 11:17 AM) *

Look at your do-while loop in your main method. You have it = myDatesList.iterator();. So, every time you iterate through that loop that line creates a new Iterator. Your code would work except for this one line. I wonder...should you remove it? Move it somewhere else? Hmmm. smile.gif



I tried removing the offending line; howvever, it just caused the program to crash when I tried to execute it... the same thing for when I moved it.... I am not sure where to move it to. and I am still lost on how to dequeue.... and my classmates haven't been much help either. Does anyone know where I can find a sample of what I am trying to do??? I looked at another post of an applet... but it used strings, and I couldn't get that example to port into my existing code. I am totally disheartened by this whole assignment...

Cobrec
User is offlineProfile CardPM
+Quote Post

Programmist
RE: Problems Enqueing/dequeing The Date
13 Jul, 2007 - 02:19 AM
Post #6

Four-letter word
Group Icon

Joined: 2 Jan, 2006
Posts: 1,250



Thanked: 11 times
Dream Kudos: 100
Expert In: Java

My Contributions
QUOTE(cobrec @ 12 Jul, 2007 - 10:29 PM) *

QUOTE(alcdotcom @ 12 Jul, 2007 - 11:17 AM) *

Look at your do-while loop in your main method. You have it = myDatesList.iterator();. So, every time you iterate through that loop that line creates a new Iterator. Your code would work except for this one line. I wonder...should you remove it? Move it somewhere else? Hmmm. smile.gif



I tried removing the offending line; howvever, it just caused the program to crash when I tried to execute it... the same thing for when I moved it.... I am not sure where to move it to. and I am still lost on how to dequeue.... and my classmates haven't been much help either. Does anyone know where I can find a sample of what I am trying to do??? I looked at another post of an applet... but it used strings, and I couldn't get that example to port into my existing code. I am totally disheartened by this whole assignment...

Cobrec

Think about this for a second. Try to understand why it's adding the same date to the queue each time. Every time you run that line a new iterator is created. When a new iterator is created its internal pointer is on the first element (Date) in the list. So, every time you iterate through the loop, you are effectively resetting the iterator to the first date in the list which is then put into the queue. What you want to do is move the initialization of the iterator outside the do-while loop. You can't just delete the line because then your code is calling it.next() when the iterator's pointer is already at the end, so you'll get an exception. So, put your initialization outside the loop. And, before you try to pull a date from the iterator, make sure you test it to see if it has a next date.

Now, as for enqueueing and dequeueing. You're using a LinkedList which implements the Java Queue interface. Look at the API link and you'll see that there are 6 methods. You can discount element() and peek() because they only allow you to view an element and don't actually change the state of the queue. So, you're left with a choice of add() and offer() to enqueue and remove() and poll() to dequeue. The pairs are basically the same and only behave differently in certain cases (e.g. when the queue is empty). Look at the API for details.

There's one more bit of OPTIONAL advice I'd give you. If you are creating a class that needs to be sorted (compared) using "natural" ordering then instead of making a comparator for it, you can just make the class implement the Comparable interface.

CODE
public class Date implements Comparable<Date> {
...
...
   // must implement this method for Comparable<Date> interface
   public int compareTo( Date otherDate) {
   ...
   ...
   }
...
)


Comparators are good for when you want to either compare a class that you may not be able to modify (like a class written by someone else) or when you want to use an ordering other than the natural ordering. Say, for instance, that your natural ordering (implemented using the Comparable interface) puts Dates in chronological order (from oldest Date to newest Date). What if you want to specify an alternate ordering, say reverse chronological order? Well, you can create a Comparator that does that an pass it in with your list of Dates. You can create any number of alternate orderings, or none at all.


User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 1/7/09 07:02PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month