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

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




ParseInteger problem, and array help

 
Reply to this topicStart new topic

ParseInteger problem, and array help

cobrec
22 Jun, 2007 - 11:26 PM
Post #1

New D.I.C Head
*

Joined: 10 Mar, 2007
Posts: 29


My Contributions
Attached File  ArrayListTest.zip ( 9.91k ) Number of downloads: 33
I am trying to modify the code below to do the following:

1. loop until the user hits enter -- which works for the most part.
2. ask the user to input a date as the string DD/MM/YYYY--- this is where the frist problem lies... the output does not parse... I receive the following errors:

Exception in thread "main" java.lang.NumberFormatException: For input string: "22/11/2000"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:456)
at java.lang.Integer.parseInt(Integer.java:497)
at ArrayListofDates2.main(ArrayListofDates2.java:122)


which tells me that line 122 has a problem....

3. I am supposed to add the above string to the array and compare the newly inputed number against the already existing numbers in the array.

4. if the number is a duplicate I am supposed to ask the user if they want to remove the duplicate.

I am a little lost on the last two parts, because the instructor did not explain them very well.

So if there is anyone out there who is good with arrays, then I would really appreciate your help.

Thanks,

Cobrec

CODE

//ArrayListofDates2.java
//example of user-defined objects in an ArrayList.
//create list of random Dates.  iterate over them.  sort them.

/*
An Iterator's next() method returns a reference of the built-in class Object.
If you want to use that reference to access a member of your class,
you must cast that return value to your class:
    Date thisDate = (Date)(it.next());
then you can access methods of the Date object:
    thisDate.getMonth()
Failure to cast will be an "incompatible types" compile error:
    //Date thisDate = it.next();   //invalid statement
Directly trying to use the it.next() to access a Date method is a
"cannot find symbol method" compile error:
    //it.next().getMonth();         //invalid statement
as the Object class does not have a getMonth member.


How can System.out.println be given an Object reference:
    System.out.println(it.next());
and the Date toString method is called?  
Object is the superclass of all other classes.  Date, for example, is a
subclass of Object, it extends Object automatically, without any need
of the extends clause.  Object is the ancestor of all classes, and so
all classes inherit its methods such as toString.
println is (indirectly) calling the toString method of Object but if a class
has overridden the toString method inherited from Object and the reference is
actually to an object of that class, then the overridden method is called.
This is the deep magic of polymorphism: a superclass reference like it.next()
can be used to access subclass methods.  
More on this later.
*/

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

public class ArrayListofDates2 {
        
    public static void main(String[] args) {
    String input;
    int size, getdate;
    int cont =JOptionPane.NO_OPTION;
    
    ArrayList myDatesList = new ArrayList();  
            
    input = JOptionPane.showInputDialog( "Enter number of random dates" );
    size = Integer.parseInt( input );
    
    //**array list of random Dates
    for (int i=1; i<=size; i++) {  
        myDatesList.add(generateRandomDate());  //**pseudo data...            
    }
    
    do{
    
    //creating the text area
    JTextArea mytextarea = new JTextArea(30,80);
    mytextarea.setLineWrap(true);
    mytextarea.setFont (new Font("Arial",Font.BOLD,18) );
    JScrollPane scrollpane = new JScrollPane(mytextarea);

    //iterate over them
    Iterator it=myDatesList.iterator();
    mytextarea.append("\n" + "Here are your dates: " + "\n" + "\n");
    
    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
        mytextarea.append( thisDate + "");
        
        //***access a method of the Date object:
        mytextarea.append("     Month is: " + thisDate.getMonth ()+ "\n");
    }
    
//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();
        mytextarea.append("\n" + "Here are your dates in sorted order: " + "\n"+ "\n");
    
    while (it.hasNext()) {
        
         mytextarea.append(it.next() + "\n");                  
    }

    //***now sort by julian day using a different comparator
    //DateComparatorJulian is defined in another file.
    Collections.sort(myDatesList,new DateComparatorJulian());   //***

    it = myDatesList.iterator();
    
    mytextarea.append("\n" + "Here are your dates in julian sorted order: " + "\n"+ "\n");
    while (it.hasNext()) {
        mytextarea.append(it.next() + "\n");          
    }

        //min and max using Comparator
        
        mytextarea.append("\n" + "Min value in array list: " +
               Collections.min(myDatesList, new DateComparator()) + "\n");
        
           mytextarea.append("\n" + "Max value in array list: " +
               Collections.max(myDatesList, new DateComparator()) + "\n");
                  
    //displays text area
    JOptionPane.showMessageDialog(null, scrollpane, "ArrayListofDates2", JOptionPane.PLAIN_MESSAGE);  
    
     cont = JOptionPane.showConfirmDialog(null,"Do you wish to add a new value?",
                         "Click Yes to Continue",JOptionPane.YES_NO_OPTION);
    
    String thedate = JOptionPane.showInputDialog("Please enter the date in the following format MM/DD/YYYY. ");    
                //getdate = Integer.parseInt(thedate);
                 
         mytextarea.append(thedate + "\n");
        
        
        } while (cont != JOptionPane.NO_OPTION);
    
    
        
    System.exit(0);
        
    }
    
    //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);
          
    }
}





This post has been edited by cobrec: 23 Jun, 2007 - 02:35 AM
User is offlineProfile CardPM
+Quote Post

PennyBoki
RE: ParseInteger Problem, And Array Help
23 Jun, 2007 - 01:57 AM
Post #2

system("revolution");
Group Icon

Joined: 11 Dec, 2006
Posts: 2,010



Thanked: 7 times
Dream Kudos: 500
Expert In: Java,C++,C

My Contributions
Hi I haven's seen this class so far DateComparator() it is yours or it needs to be imported?
And your problem is in here:
QUOTE
getdate = Integer.parseInt(date);

You cant parse e.g. 3/3/5210
because of the /

so you'll need to add few functions from which you'll get the desired numbers as a string, then you can parse only the number.

like:
CODE
int getmonth;
String tmp1 = date.substring(0,indexOf("/"));
getmonth = Integer.parseInt(tmp1);


...
you'll do the same for the day and the year
well almost the same wink2.gif

This post has been edited by PennyBoki: 23 Jun, 2007 - 05:25 AM
User is offlineProfile CardPM
+Quote Post

Programmist
RE: ParseInteger Problem, And Array Help
23 Jun, 2007 - 12:11 PM
Post #3

Four-letter word
Group Icon

Joined: 2 Jan, 2006
Posts: 1,250



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

My Contributions
I'm going to tell you about a "trick" that will make your life easier. Check out the SimpleDateFormat class in the Java API. If you create the SimpleDateFormat the correct way, there is a method that will take a date string like the one you use and automatically convert it to a Date class. How F-ing cool is that. Someone has already done all the work for you. I'll give you a big hint:
CODE
SimpleDateFormat sdf = new SimpleDateFormat(???);
try {
    Date d = sdf.parse(???);
    
} catch (ParseException e) {
    e.printStackTrace();
}


I've put question marks where you need to fill in the blanks. Go look at the API. You'll also see links to inherited methods from the superclasses. You may want look at the parse method of the superclass DateFormat, for your purposes.
User is offlineProfile CardPM
+Quote Post

cobrec
RE: ParseInteger Problem, And Array Help
23 Jun, 2007 - 09:36 PM
Post #4

New D.I.C Head
*

Joined: 10 Mar, 2007
Posts: 29


My Contributions
QUOTE(alcdotcom @ 23 Jun, 2007 - 01:11 PM) *

I'm going to tell you about a "trick" that will make your life easier. Check out the SimpleDateFormat class in the Java API. If you create the SimpleDateFormat the correct way, there is a method that will take a date string like the one you use and automatically convert it to a Date class. How F-ing cool is that. Someone has already done all the work for you. I'll give you a big hint:
CODE
SimpleDateFormat sdf = new SimpleDateFormat(???);
try {
    Date d = sdf.parse(???);
    
} catch (ParseException e) {
    e.printStackTrace();
}


I've put question marks where you need to fill in the blanks. Go look at the API. You'll also see links to inherited methods from the superclasses. You may want look at the parse method of the superclass DateFormat, for your purposes.


I went to the SimpleDateFormat link on the Java page, but apparently I am pretty dumb, because I apparently don't understand how to implent this.... I tried to implent it like this...


CODE


    
String thedate = JOptionPane.showInputDialog("Please enter the date in the following format MM/DD/YYYY. ");    
                //getdate = Integer.parseInt(thedate);
                 
        
         SimpleDateFormat sdf = new SimpleDateFormat(thedate);
        try {
            Date d = sdf.parse(thedate);
    
        } catch (ParseException e) {
        e.printStackTrace();
        }
        mytextarea.append(thedate + "\n");
        



and I get the following errors:

cannot find symbol class SimpleDateFormat line 128
cannot find symbol class SimpleDateFormat line 128
cannot find symbol class ParseException line 132

When I add:

CODE

public class SimpleDateFromat extends DateFormat {

to the front of the above code, it really crashes, giving me too many errors to list....

I am confused about this part ARGH!!!


User is offlineProfile CardPM
+Quote Post

Programmist
RE: ParseInteger Problem, And Array Help
24 Jun, 2007 - 05:07 PM
Post #5

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 @ 23 Jun, 2007 - 10:36 PM) *

I went to the SimpleDateFormat link on the Java page, but apparently I am pretty dumb, because I apparently don't understand how to implent this.... I tried to implent it like this...


CODE

String thedate = JOptionPane.showInputDialog("Please enter the date in the following format MM/DD/YYYY. ");    
                //getdate = Integer.parseInt(thedate);
                 
        
         SimpleDateFormat sdf = new SimpleDateFormat(thedate);
        try {
            Date d = sdf.parse(thedate);
    
        } catch (ParseException e) {
        e.printStackTrace();
        }
        mytextarea.append(thedate + "\n");



You're close. The way it works is that you put the "pattern" in the constructor and you put the actual date data in the parse method. The API tells you how the patterns work. In this cases, it even has examples. Get used to using the API and it can be your best friend

CODE

SimpleDateFormat sdf = new SimpleDateFormat("some-pattern-string-here");
try {
       Date d = sdf.parse("01/01/2007"); <--actual date string here
    
} catch (ParseException e) {
    e.printStackTrace();
}


QUOTE(cobrec @ 23 Jun, 2007 - 10:36 PM) *

and I get the following errors:


cannot find symbol class SimpleDateFormat line 128
cannot find symbol class SimpleDateFormat line 128
cannot find symbol class ParseException line 132

These errors are because you have not imported the SimpleDateFormat class or the ParseException class.

QUOTE(cobrec @ 23 Jun, 2007 - 10:36 PM) *

When I add:

CODE

public class SimpleDateFromat extends DateFormat {

to the front of the above code, it really crashes, giving me too many errors to list....

I am confused about this part ARGH!!!

Why would you even do that? Don't do that. smile.gif
User is offlineProfile CardPM
+Quote Post

cobrec
RE: ParseInteger Problem, And Array Help
24 Jun, 2007 - 06:08 PM
Post #6

New D.I.C Head
*

Joined: 10 Mar, 2007
Posts: 29


My Contributions
Ok,

the fact that I am so close is KILLING ME....

CODE
    
String thedate = JOptionPane.showInputDialog("Please enter the date in the following format MM/DD/YYYY. ");
SimpleDateFormat sdf = new SimpleDateFormat("MM/DD/YYYY");
        try {
            Date d = sdf.parse(thedate);
    
        } catch (ParseException e) {
        e.printStackTrace();
        }
        mytextarea.append(thedate + "\n");


I don't see the problem with this, however, I get an incompatible types error on this line....

CODE

Date d = sdf.parse(thedate);


the way I understand this line is that it is supposed to parse the (thedate) into an iteger.... so why is it giving me an error.... I know strings and ints don't play well together.....

then I still have to figure out why the results do not print... and add the input to the array. after it checks to see if it's a duplicate, and give the user an option to delete the duplicate.... all in about 3 hrs..... or it's late again!!!!

ARGH!!!
User is offlineProfile CardPM
+Quote Post

Programmist
RE: ParseInteger Problem, And Array Help
24 Jun, 2007 - 06:45 PM
Post #7

Four-letter word
Group Icon

Joined: 2 Jan, 2006
Posts: 1,250



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

My Contributions
From the SimpleDateFormat API:
QUOTE

y Year e.g. 1996; 96
M Month in year e.g. July; Jul; 07
D Day in year e.g. 189
d Day in month e.g. 10

The case of the letter you use matters.

The parse method that SimpleDateFormat inherits from DateFormat takes a String and returns a Date object. It's simple...hence the name SimpleDateformat. So, put the date string into the parse method and you get a date. If you're getting an incompatible types method then you are doing something wrong. I can't help you more because you didn't post the actual error which might have contained more information. And now I've got to go to bed. Let me give you an example of a something I used when parsing XML for date info in an RSS reader I wrote a few years ago. If this doesn't help you, then try Google for some more examples. Good luck.

CODE
SimpleDateFormat sdf5 = new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss Z");
...
...

// dateIn is a string like "Wed, 4 Jul 2001 12:08:56 -0700"
sdf5.parse( dateIn ) <-- returns a Date object
...
...


This post has been edited by alcdotcom: 24 Jun, 2007 - 06:46 PM
User is offlineProfile CardPM
+Quote Post

cobrec
RE: ParseInteger Problem, And Array Help
28 Jun, 2007 - 06:49 PM
Post #8

New D.I.C Head
*

Joined: 10 Mar, 2007
Posts: 29


My Contributions
Progress?

Ok, here is the updated progam... the date almost works.... but for some reason the loop does not.....

also, if you entera date like 1/1/2000 the program breaks....so you must enter it as 01/01/2000.

but even if it matches....it gives the wrong message.

CODE

//ArrayListofDates2.java
//example of user-defined objects in an ArrayList.
//create list of random Dates.  iterate over them.  sort them.

/*
An Iterator's next() method returns a reference of the built-in class Object.
If you want to use that reference to access a member of your class,
you must cast that return value to your class:
    Date thisDate = (Date)(it.next());
then you can access methods of the Date object:
    thisDate.getMonth()
Failure to cast will be an "incompatible types" compile error:
    //Date thisDate = it.next();   //invalid statement
Directly trying to use the it.next() to access a Date method is a
"cannot find symbol method" compile error:
    //it.next().getMonth();         //invalid statement
as the Object class does not have a getMonth member.


How can System.out.println be given an Object reference:
    System.out.println(it.next());
and the Date toString method is called?  
Object is the superclass of all other classes.  Date, for example, is a
subclass of Object, it extends Object automatically, without any need
of the extends clause.  Object is the ancestor of all classes, and so
all classes inherit its methods such as toString.
println is (indirectly) calling the toString method of Object but if a class
has overridden the toString method inherited from Object and the reference is
actually to an object of that class, then the overridden method is called.
This is the deep magic of polymorphism: a superclass reference like it.next()
can be used to access subclass methods.  
More on this later.
*/

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

public class ArrayListofDates2 {
        
    public static void main(String[] args) {
    String input;
    int size, getdate;
    int getmonth,getday,getyear;
    int cont =JOptionPane.NO_OPTION;
    
    ArrayList myDatesList = new ArrayList();
      
            
    input = JOptionPane.showInputDialog( "Enter number of random dates" );
    size = Integer.parseInt( input );
    
    //**array list of random Dates
    for (int i=1; i<=size; i++) {  
        myDatesList.add(generateRandomDate());  //**pseudo data...            
    }
    
    do{
    

    //creating the text area
    JTextArea mytextarea = new JTextArea(30,60);
    mytextarea.setLineWrap(true);
    mytextarea.setFont (new Font("Arial",Font.BOLD,18) );
    JScrollPane scrollpane = new JScrollPane(mytextarea);

    //iterate over them
    Iterator it=myDatesList.iterator();
    mytextarea.append("\n" + "Here are your dates: " + "\n" + "\n");
    
    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
        mytextarea.append( thisDate + "");
        
        //***access a method of the Date object:
        mytextarea.append("     Month is: " + thisDate.getMonth ()+ "\n");
    }
    
//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();
        mytextarea.append("\n" + "Here are your dates in sorted order: " + "\n"+ "\n");
    
    while (it.hasNext()) {
        
         mytextarea.append(it.next() + "\n");                  
    }

    //***now sort by julian day using a different comparator
    //DateComparatorJulian is defined in another file.
    Collections.sort(myDatesList,new DateComparatorJulian());   //***

    it = myDatesList.iterator();
    
    mytextarea.append("\n" + "Here are your dates in julian sorted order: " + "\n"+ "\n");
    while (it.hasNext()) {
        mytextarea.append(it.next() + "\n");          
    }

        //min and max using Comparator
        
        mytextarea.append("\n" + "Min value in array list: " +
               Collections.min(myDatesList, new DateComparator()) + "\n");
        
           mytextarea.append("\n" + "Max value in array list: " +
               Collections.max(myDatesList, new DateComparator()) + "\n");

    
                  
    //displays text area
    JOptionPane.showMessageDialog(null, scrollpane, "ArrayListofDates2", JOptionPane.PLAIN_MESSAGE);  
  

            
     cont = JOptionPane.showConfirmDialog(null,"Do you wish to search for a  value?",
                         "Click Yes to Continue",JOptionPane.YES_NO_OPTION);
                    
    String thedate = JOptionPane.showInputDialog("Please enter the date in the following format MM/DD/YYYY. ");
    
         getmonth=Integer.parseInt(thedate.substring(0,1));
         getday=Integer.parseInt(thedate.substring(3,4));
         getyear=Integer.parseInt(thedate.substring(6,9));
    
    Date compdate=new Date (getmonth,getday,getyear);

        
        {if(myDatesList.contains(compdate))
        JOptionPane.showMessageDialog(null,"The array contains:" + compdate);
        
        else
            JOptionPane.showMessageDialog(null,"The array does not contain:" + compdate);
        
        }
        
        
        //mytextarea.append(thedate + "\n");
        
        

        } while (cont != JOptionPane.NO_OPTION);
        
    System.exit(0);
    
             
    }
    
    //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);
          
    }
}




Cobrec

This post has been edited by cobrec: 28 Jun, 2007 - 07:25 PM
User is offlineProfile CardPM
+Quote Post

Programmist
RE: ParseInteger Problem, And Array Help
29 Jun, 2007 - 02:26 AM
Post #9

Four-letter word
Group Icon

Joined: 2 Jan, 2006
Posts: 1,250



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

My Contributions
I can help you with the date portion. Since you are getting user input you should validate what they are entering. First, make sure it's in the general format you want by using the classes in Java's regex package. You can have several valid patterns, e.g. 1/1/06, 01/01/2006, 1/22/2006, etc. If you're unfamiliar with the java.util.regex package Google tutorials for it. If you are unfamiliar with regular expressions...well...learn how to use them and your life will be easier (the programming part of it anyway). Once input has been validated, you'll know which pattern to choose to create you SimpleDateFormat. Here's some pseudocode:

CODE
sdf[]  // array containing SimpleDateFormats created
         // with pattern strings
regex[]  // regular expressions describing those patterns
userInput // pretend String variable holding user input
for(int i = 0; i < sdf.length; i++) {
   if( userInput matches regex[i] ) {
      sdf[i].parse(userInput)
   }
}


This post has been edited by alcdotcom: 29 Jun, 2007 - 02:27 AM
User is offlineProfile CardPM
+Quote Post

cobrec
RE: ParseInteger Problem, And Array Help
30 Jun, 2007 - 03:00 AM
Post #10

New D.I.C Head
*

Joined: 10 Mar, 2007
Posts: 29


My Contributions
Thanks for all the help... I couldn't have finished this thing with out everyone's help. I am submitting the code here, so if anyone else has problems, or wishes to improve on this code they can. I hope that they do, because I can see this type of code being useful in other types of projects. anyway... here it is.

Cobrec

CODE

/**
* Name: John R. Peck
* @Course:    CMIS 241A/Professor Wills
* @Assignment#: 3
* @(#)ArrayListofDates2.java
* @version 1.02A 2007/3/27
*/


//ArrayListofDates2.java
//example of user-defined objects in an ArrayList.
//create list of random Dates.  iterate over them.  sort them.

/*
An Iterator's next() method returns a reference of the built-in class Object.
If you want to use that reference to access a member of your class,
you must cast that return value to your class:
    Date thisDate = (Date)(it.next());
then you can access methods of the Date object:
    thisDate.getMonth()
Failure to cast will be an "incompatible types" compile error:
    //Date thisDate = it.next();   //invalid statement
Directly trying to use the it.next() to access a Date method is a
"cannot find symbol method" compile error:
    //it.next().getMonth();         //invalid statement
as the Object class does not have a getMonth member.


How can System.out.println be given an Object reference:
    System.out.println(it.next());
and the Date toString method is called?  
Object is the superclass of all other classes.  Date, for example, is a
subclass of Object, it extends Object automatically, without any need
of the extends clause.  Object is the ancestor of all classes, and so
all classes inherit its methods such as toString.
println is (indirectly) calling the toString method of Object but if a class
has overridden the toString method inherited from Object and the reference is
actually to an object of that class, then the overridden method is called.
This is the deep magic of polymorphism: a superclass reference like it.next()
can be used to access subclass methods.  
More on this later.
*/

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

public class ArrayListofDates2 {
        
    public static void main(String[] args) {
    String input;
    int size, getdate;
    int getmonth,getday,getyear;
    int cont =JOptionPane.NO_OPTION;
    
    ArrayList myDatesList = new ArrayList();
      
            
    input = JOptionPane.showInputDialog( "Enter number of random dates" );
    size = Integer.parseInt( input );
    
    //**array list of random Dates
    for (int i=1; i<=size; i++) {  
        myDatesList.add(generateRandomDate());  //**pseudo data...            
    }
    
    do{
    

    //creating the text area
    JTextArea mytextarea = new JTextArea(30,60);
    mytextarea.setLineWrap(true);
    mytextarea.setFont (new Font("Arial",Font.BOLD,18) );
    JScrollPane scrollpane = new JScrollPane(mytextarea);

    //iterate over them
    Iterator it=myDatesList.iterator();
    mytextarea.append("\n" + "Here are your dates: " + "\n" + "\n");
    
    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
        mytextarea.append( thisDate + "");
        
        //***access a method of the Date object:
        mytextarea.append("     Month is: " + thisDate.getMonth ()+ "\n");
    }
    
//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();
        mytextarea.append("\n" + "Here are your dates in sorted order: " + "\n"+ "\n");
    
    while (it.hasNext()) {
        
         mytextarea.append(it.next() + "\n");                  
    }

    //***now sort by julian day using a different comparator
    //DateComparatorJulian is defined in another file.
    Collections.sort(myDatesList,new DateComparatorJulian());   //***

    it = myDatesList.iterator();
    
    mytextarea.append("\n" + "Here are your dates in julian sorted order: " + "\n"+ "\n");
    while (it.hasNext()) {
        mytextarea.append(it.next() + "\n");          
    }

        //min and max using Comparator
        
        mytextarea.append("\n" + "Min value in array list: " +
               Collections.min(myDatesList, new DateComparator()) + "\n");
        
           mytextarea.append("\n" + "Max value in array list: " +
               Collections.max(myDatesList, new DateComparator()) + "\n");

    //displays text area
    JOptionPane.showMessageDialog(null, scrollpane, "ArrayListofDates2", JOptionPane.PLAIN_MESSAGE);  
                  
                
     cont = JOptionPane.showConfirmDialog(null,"Do you wish to search for a  value?",
                         "Click Yes to Continue",JOptionPane.YES_NO_OPTION);
                    
    String thedate = JOptionPane.showInputDialog("Please enter the date in the following format MM/DD/YYYY. ");
        Date compdate = new Date(thedate);
          
        {if(myDatesList.contains(compdate))
        {
        JOptionPane.showMessageDialog(null,"The array contains:" + compdate);
        JOptionPane.showConfirmDialog(null,"Do you wish to delete this value?",
             "Click Yes to Continue",JOptionPane.YES_NO_OPTION);
             if (cont != JOptionPane.NO_OPTION);
             {myDatesList.remove(compdate);
             
             }
        }
        else
            JOptionPane.showMessageDialog(null,"The array does not contain:" + compdate);
            
        }
        //iterate over them
    it=myDatesList.iterator();
    //mytextarea.append("\n" + "Here are your new dates: " + "\n" + "\n");
    
      
    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
        //mytextarea.append( thisDate + "");  
    }
        
    //displays text area
    //JOptionPane.showMessageDialog(null,scrollpane,"ArrayListofDates2", JOptionPane.PLAIN_MESSAGE);
                    
    }while (cont != JOptionPane.NO_OPTION);
        
    System.exit(0);
    }
    //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