1 2 Previous Next 20 Replies Latest reply on Oct 13, 2009 3:24 PM by 3004

    Parsing a date error.help with small program

    843789
      I would like to read from a file which the user can choose on start of program. I want to read line for line, checking if the format of each is ok. if it is , I add it to ArrayList of good books, if not I add it to ArrayList of error books. The date isnt parsing correctly.
      import java.io.*;
      import java.text.DateFormat;
      import java.text.ParseException;
      import java.text.SimpleDateFormat;
      import java.util.*;
      public class Book {
      
      
          String isbn;
          int copyNumber;
          String title;
          String author;
          int statistics;
          Date borrowDate = new Date();
          Date returnDate = new Date();
          int libraryCardNumber;
          DateFormat formatter = new SimpleDateFormat("yy/mm/dd");
      
      public Book(String newIsbn, int newCopyNumber, String newTitle, String newAuthor,
              int newStatistics, Date newBorrowDate, Date newReturnDate, int newLibraryCardNumber)
      {
          isbn = newIsbn;
          copyNumber = newCopyNumber;
          title = newTitle;
          author = newAuthor;
          statistics = newStatistics;
          borrowDate = newBorrowDate;
          returnDate = newReturnDate;
          libraryCardNumber = newLibraryCardNumber;
      }
      
      public Book(){
      
      }
      
      public Book(String newRow) throws ParseException
      {
          String[] token = newRow.split("#");
          
                      isbn = token[0];
                      copyNumber = Integer.parseInt(token[1]);
                      title = token[2];
                      author = token[3];
                      statistics = Integer.parseInt(token[4]);
                      borrowDate = (Date)formatter.parse(token[5]);
                      returnDate = (Date)formatter.parse(token[6]);
                      libraryCardNumber = Integer.parseInt(token[7]);
      }
      
      public String getIsbn()
          {
           return isbn;
          }
      
      public void setIsbn(String isbn)
          {
          this.isbn = isbn;
          }
      
      public int getCopyNumber()
      {
          return copyNumber;
      }
      
      public void setCopyNumber(int copyNumber)
      {
          this.copyNumber = copyNumber;
      }
      
      public String getTitle()
      {
          return title;
      }
      
      private void setTitle(String title)
      {
          this.title = title;
      }
      
      public String getAuthor()
      {
          return author;
      }
      
      private void setAuthor(String author)
      {
          this.author = author;
      }
      
      public int getStatistics()
      {
          return statistics;
      }
      
      public void setStatistics(int statistics)
      {
          this.statistics = statistics;
      }
      
      public Date setBorrowDate()
      {
          return borrowDate;
      }
      
      public void getBorrowDate(Date borrowDate)
      {
          this.borrowDate = borrowDate;
      }
      
      public Date getReturnDate()
      {
          return returnDate;
      }
      
      public void setReturnDate (Date returnDate)
      {
          this.returnDate = returnDate;
      }
      
      public int getLibraryCardNumber()
      {
          return libraryCardNumber;
      }
      
      public void setLibraryNumber(int libraryCardNumber)
      {
          this.libraryCardNumber = libraryCardNumber;
      }
      
      
      }
      import java.io.*;
      import java.text.ParseException;
      import java.util.*;
      import java.util.regex.Matcher;
      import java.util.regex.Pattern;
      import javax.swing.JFileChooser;
      
      
      public class WriteFromBookFile {
      
          private static Pattern pattern;
      
          public static void main(String[] args) throws FileNotFoundException, ParseException, IOException {
      
              JFileChooser fileChooser = new JFileChooser();
              if(fileChooser.showOpenDialog(null)
                      == JFileChooser.APPROVE_OPTION){
              ArrayList<Book> newBooks = new ArrayList<Book>();
              ArrayList<Book> errorBooks = new ArrayList<Book>();
      
      
              java.io.File file = fileChooser.getSelectedFile();
          //  try{  BufferedReader reader = new BufferedReader(new FileReader("books.txt"));
             Scanner input = new Scanner(file);
             String line = input.nextLine();
              while (line != null) {
      
      
                  Book newBook = new Book(line);
      
                  String[] newToken = line.split("#");
      
                  pattern = Pattern.compile("ISBN\\x20(?=.{13}$)\\d{1,5}([- ])\\d{1,7}\\1\\d{1,6}\\1(\\d|X)$");
                  Matcher matchIsbn = pattern.matcher(newToken[0]);
                  pattern = Pattern.compile("[\\d]+");
                  Matcher matchCopyNumber = pattern.matcher(newToken[1]);
                  pattern = Pattern.compile("[\\D&&\\w]+");
                  Matcher matchTitle = pattern.matcher(newToken[2]);
                  pattern = Pattern.compile("[\\D&&\\w]+");
                  Matcher matchAuthor = pattern.matcher(newToken[3]);
                  pattern = Pattern.compile("[\\d]+");
                  Matcher matchStatistics = pattern.matcher(newToken[4]);
                  pattern = Pattern.compile("YY/MM/DD");
                  Matcher matchBorrowDate = pattern.matcher(newToken[5]);
                  pattern = Pattern.compile("YY/MM/DD");
                  Matcher matchReturnDate = pattern.matcher(newToken[6]);
                  pattern = Pattern.compile("[\\d]+");
                  Matcher matchLibraryCardNumber = pattern.matcher(newToken[7]);
      
                  /*  if(matchIsbn.matches(newBook.getIsbn()) && matchCopyNumber.matches(newBook.getCopyNumber())
                  && matchTitle.matches(newBook.getTitle()) && matchAuthor.matches(newBook.getAuthor())
                  && matchStatistics.matches(newBook.getStatistics()) && matchBorrowDate.matches(newBook.getBorrowDate())
                  && matchReturnDate.matches(newBook.getReturnDate()) && matchLibraryCardNumber.matches(newBook.getLibraryCardNumber()));*/
                  if (matchIsbn.matches() && matchCopyNumber.matches() && matchTitle.matches() && matchAuthor.matches()
                          && matchStatistics.matches() && matchBorrowDate.matches() && matchReturnDate.matches() && matchLibraryCardNumber.matches())
      
                  {
                      newBooks.add(newBook);
                  }
                         else
                      errorBooks.add(newBook);
                  
      
      line = input.nextLine();
          }
      input.close();
      
             java.io.File newBookFile = new java.io.File("newBook.txt");
      
          if(newBookFile.exists()){
              System.out.println("File exists.");
              System.exit(0);
          }
      
          java.io.PrintWriter output = new java.io.PrintWriter(newBookFile);
      
          for(int i = 0; i < newBooks.size(); i++)
          {
              output.print(newBooks.get(i));
          }
              output.close();
          }
      }
      }
        • 1. Re: Parsing a date error.help with small program
          b_faissal
          You must read the API spec [http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html|http://java.sun.com/j2se/1.5.0/docs/api/java/text/SimpleDateFormat.html]

          in pattern m (lowercase) is use for minutes not for month , you should use M (uppercase) instead :
          "yy/MM/dd"
          • 2. Re: Parsing a date error.help with small program
            843789
            Your lines here confuse me:
                        pattern = Pattern.compile("YY/MM/DD");
                        Matcher matchBorrowDate = pattern.matcher(newToken[5]);
                        pattern = Pattern.compile("YY/MM/DD");
                        Matcher matchReturnDate = pattern.matcher(newToken[6]);
            It looks as if you are trying to use regex to match or parse dates, and if so, that doesn't look like it should work so well. Myself, I'd use a SimpleDateFormat object (check the API for how to use it), and I'd create a small test file of dates to check it on, rather than have it buried in a large class. Also, if you do the small file and small program, it will be easier for you to debug and for us to go through if something goes wrong. Your current posted class has too much code that's not related to the problem making it difficult for those who would help you. Much luck.

            edit: I see that faissal has provided you with the link.

            Edited by: Encephalopathic on Oct 12, 2009 2:14 PM
            • 3. Re: Parsing a date error.help with small program
              3004
              That's an awful lot of irrelevant code for a question about parsing dates. Embrace the SSCCE.
              • 4. Re: Parsing a date error.help with small program
                3004
                Also, I thought you'd know by now that, "The date isnt parsing correctly," contains no useful information. Didn't we get the idea of providing details into your head in your earlier threads?
                • 5. Re: Parsing a date error.help with small program
                  843789
                  I know. sorry, I never knew what to call it.

                  wont happen again.

                  Is there not another way to compare formats for the user fields?

                  It feels like im checking the lines from the file twice. once in the while loop and once in the constructor.

                  I have looked over the simpleDateFormat. but where would that be placed. with the other checks?
                  • 6. Re: Parsing a date error.help with small program
                    843789
                    Implode wrote:
                    It feels like im checking the lines from the file twice. once in the while loop and once in the constructor.
                    I have looked over the simpleDateFormat. but where would that be placed. with the other checks?
                    Try using it yourself in a small program. That will give you the feel for it, and then you'll likely be able to figure out how to use it.
                    • 7. Re: Parsing a date error.help with small program
                      843789
                      My program seems to work, the thing I cant work out is that because I try to match 8 fields using split
                      String[] newToken = line.split("#");
                      
                                  pattern = Pattern.compile("ISBN\\x20(?=.{13}$)\\d{1,5}([- ])\\d{1,7}\\1\\d{1,6}\\1(\\d|X)$");
                                  Matcher matchIsbn = pattern.matcher(newToken[0]);
                                  pattern = Pattern.compile("[\\d]+");
                                  Matcher matchCopyNumber = pattern.matcher(newToken[1]);
                                  pattern = Pattern.compile("[\\D&&\\w]+");
                                  Matcher matchTitle = pattern.matcher(newToken[2]);
                                  pattern = Pattern.compile("[\\D&&\\w]+");
                                  Matcher matchAuthor = pattern.matcher(newToken[3]);
                                  pattern = Pattern.compile("[\\d]+");
                                  Matcher matchStatistics = pattern.matcher(newToken[4]);
                                  pattern = Pattern.compile("YYMMDD");
                                  Matcher matchBorrowDate = pattern.matcher(newToken[5]);
                                  pattern = Pattern.compile("YYMMDD");
                                  Matcher matchReturnDate = pattern.matcher(newToken[6]);
                                  pattern = Pattern.compile("[\\d]+");
                                  Matcher matchLibraryCardNumber = pattern.matcher(newToken[7]);
                      because some lines dont have 8 tokens, there is an array out of bounds error.

                      How can it just move to the next token if there isnt a token to match or to the next line if there aren't enough tokens?
                      • 8. Re: Parsing a date error.help with small program
                        3004
                        Implode wrote:
                        pattern = Pattern.compile("YYMMDD");
                        What do you think this will match? Regex doesn't know anything about dates or date format symbols.
                        • 9. Re: Parsing a date error.help with small program
                          843789
                          i found this on regexlib

                          ^((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012])(0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229)$

                          when I tried it, it caused these lines to error
                                      Matcher matchCopyNumber = pattern.matcher(newToken[1]);
                                      pattern = Pattern.compile("[\\D&&\\w]+");
                                      Matcher matchTitle = pattern.matcher(newToken[2]);
                                      pattern = Pattern.compile("[\\D&&\\w]+");
                                      Matcher matchAuthor = pattern.matcher(newToken[3]);
                                      pattern = Pattern.compile("[\\d]+");
                                      Matcher matchStatistics = pattern.matcher(newToken[4]);
                          or is shows errors on the regexlib statement, saying illegal escape characters

                          Edited by: Implode on Oct 12, 2009 3:48 PM
                          • 10. Re: Parsing a date error.help with small program
                            3004
                            Don't use regex to validate the date.

                            You can use it to verify that there are digits and slashes in yy/mm/dd format, or whatever format you're looking for, but really you should be using SimpleDateFormat to validate the date.
                            • 11. Re: Parsing a date error.help with small program
                              3004
                              Implode wrote:
                              or is shows errors on the regexlib statement, saying illegal escape characters
                              Regex is not something to be copied and pasted without grokking what it means.

                              One of the very basic, fundamental things you need to know about regex in Java (and strings in Java in general) is that the backslash character has special meaning both in String literals and in regex.

                              So if you have
                              \d
                              in a file or user input to indicate "digit", then the equivalent in a String literal in your Java source code will be
                              "\\d"
                              • 12. Re: Parsing a date error.help with small program
                                843789
                                Agree. Why do you feel married to a regex solution when a better solution has been suggested at least 5 or more times above.

                                Frustration++;
                                • 13. Re: Parsing a date error.help with small program
                                  843789
                                  I tried this, but I guess it doesnt check if the values fit into day month year

                                  pattern = Pattern.compile("\\d{2}\\d{2}\\d{2}");

                                  But i still get an array out of bounds error
                                  • 14. Re: Parsing a date error.help with small program
                                    843789
                                    Our posts are crossing.

                                    :(

                                    I have looked at all methods mentioned by members on this topic, but Im new to this and have no idea how to validate using simpleDateFormat.

                                    Would I use try and catch?

                                    So maybe it is better to use try and catch after every token from the split string? But how could I tell the method that if an exception is found add the line to errorLine array, if no catch found then add to goodLine array?
                                    1 2 Previous Next