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!
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. */
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
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(???);
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'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(???);
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);
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);
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
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);
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!!!!
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
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. */
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. ");
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
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
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.
//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. */
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);