Txt file read in- StringTokenizer- Try Block Catch for errors

Hello
So I am having a few issues with a school project. First is with my ReadWithScanner. It does not read in the file giving me a NullPointerException error on the line <Scanner in = new>. I have tried a few other read in files and they do not seem to be working.
I am also stuck on the logic on the try block catch statement. How does a person set up a �custom� try block that looks for errors like the ones below? I have attempted to start in the commented code.
The text file has to read in 1000 individual lines of code and are separated by �;� and should be separated into tokens with the StringTokenizer class what I attempted to do below also. Both are mere attempts and need help�
This is some what of the logic I thought of doing
1.Read the first line in first with the scanner class
2.use delimiter separated by �;�
3.Tokenizer the line into separate tokens- invoiceCode, fName, lName�
4.Check classes- check Name, check Date, checkPrice, checkPrice, checkGenre, checkShippingDate invoiceCode = "Error Code" checkInvoiceCode(String invoiceCode)checkName(String name), checkPrice(String price), checkGenre(String genre)
5.Apply the regular expressions to each try block statement
a.Assign a letter to each error for example if invoice was to short it would be assigned a letter A
b.If invoice does have the right characters it would be assigned B
c.If name has to few words it would be assigned D
d.�
This is an example of a good field from the text file
XYG726;Smith,Mr. John M.;29.96;comedy;101008;100604
Not so good line
Lu15;Will, Mark;50.00;Science;030305;030807
The file should then be printed out in the program not to a text file. It only needs to print the invoice number and error code letter assignment.
If you have any questions feel free to let me know. Thanks for all or any help you have to offer.
Invoice
Three upper case letters followed by three digits
Regular Expression "[A-Z]{3}[0-9]{3}"
Customer Name
Should be in the form: last name followed by a <,> optional title (Mrs. Mrs�) then first name optional middle initial Titles must be
So regular expression something like �[a-z][A-Z]+([A-Z]{1}?[a-z][./})+[a-z][A-Z]�
Sale Price
Two decimal digits to the left of the decimal point. The price should not have a leading zero.
Regular Expression [0-9]{2}*./[0-9]
Genre
The genre should only contain lowercase letters. Regular expression �[a-z]�
ShipDate and Order Date-
Must be standard dates- MMDDYY. The order date and shipping date has to be after today�s date. Regular expression �[0-9]{2}+[0-9]{2}+[0-9]{2}�
package Project3;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.util.Scanner;
public class ReadWithScanner {
private final File fFile;
public static void main (String args[]){
Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
Scanner.processLineByLine();
public ReadWithScanner(String aFileName){
fFile = new File(aFileName);
public final void processLineByLine(){
try {
//use a Scanner to get each line
Scanner scanner = new Scanner(fFile);
while ( scanner.hasNextLine() ){
processLine( scanner.nextLine() );
scanner.close();
catch (IOException ex){
protected void processLine(String aLine){
//use a second scanner again to raed the content of each line
Scanner scanner = new Scanner(aLine);
scanner.useDelimiter(";");
if (scanner.hasNext() ){
//read each file?
String name = scanner.next();
String value = scanner.next();
else {
scanner.close();
//Token Names that are seperated
StringTokenizer st;
String invoiceCode = st.nextToken();
String fname = st.nextToken();
String lname = st.nextToken();
String price = st.nextToken();
String genre = st.nextToken();
String orderDate = st.nextToken();
String shipDate = st.nextToken();
String invoiceCode;
invoiceCode = "A" checkInvoiceCode(String invoiceCode);
Pattern p = Pattern.compile("[a-z]{6}[A-Z]{6}[0-9]{6}");
Matcher m = p.matcher(invoiceCode);
p.matcher(invoiceCode);
if(m.matches()) {
System.out.println(invoiceCode);
else {
System.out.println ("A");
try
invoiceCode = Integer.parseInt(String);
catch (NumberFormatException e)
{ System.out.println ("B"); System.exit(1); }
*/

I have made a quite a few updates to my code. Please look it over again. I have also made many comments to help with the logic. Once again if you have any questions please feel free to ask. Sorry about not using the tags before- I was no aware of them. Thanks for the advice sabre150.
package Project3;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.*;
import java.util.Scanner;
public class ReadWithScanner {
     private final File fFile;
     public static void main (String args[]){
               //read in text file from directory currently it can not read the file
              Scanner in = new Scanner(new File("e:\\work_space_java\\Project\\Package3\\movie.txt"));
              //Scans each line of the text in
              Scanner.processLineByLine();
            //assigns new file name to file
            public ReadWithScanner(String aFileName){
              fFile = new File(aFileName); 
            public final void processLineByLine(){
              try {
                //use a Scanner to get each line from the processLineByLine
                Scanner scanner = new Scanner(fFile);
                while ( scanner.hasNextLine() ){
                  processLine( scanner.nextLine() );
                scanner.close();
              catch (IOException ex){
            protected void processLine(String aLine){
              //use a second scanner again to read the content of each line
               //delmiter should then break each line in the text file into seperate "tokens"
              Scanner scanner = new Scanner(aLine);
              scanner.useDelimiter(";");
              if (scanner.hasNext() ){
                   //reads each line from scanner
                String name = scanner.next();
              else {
              scanner.close();
           /*Convert Tokens from Scanner into String Tokenizer with assigment to each variable
            * I am missing something
            * Need to convert each line read from the scanner (name variable) to the String
            * Tokenizer class
          //Tokens names now assigned a varaible
          StringTokenizer st;
          String invoice = st.nextToken();
          String name = st.nextToken();
          String price  = st.nextToken();
          String genre = st.nextToken();
          String orderDate = st.nextToken();
          String shipDate = st.nextToken();
      /*If statments (Try Block Statements?) with Regular Expressions
      * This is where I have the most issues on how to set up
      * "custom" try and block errors trying to match what I have
      * in the regular expressions. 
      * I believe try and catch statements
      * make this easier but I have used 'match' and 'pattern' with if
      * statments.  If try block statements are easier please show!
      * Regular Expressions may not be correct either
       invoice = checkInvoiceCode(invoice);
       //Defined cerita for Inovice are:
       //Error A = Invoice code is too short  
       //Error B = Invoice code does not have the right characters 
       //Error C = Invoice code digits are all zero
       //Checks for error A
       //Has at least six characters
        Pattern invoiceShort = Pattern.compile("{6}");
        Matcher shortInvoice = invoiceShort.matcher(invoice);
        p.matcher(invoiceCode);
        if(m.matches()) {
             System.out.println(invoice);      
        else {
             System.out.println ("A");
        //Checks for error B
        //3 Upper Case Letters followed by three numbers,
        Pattern rightChar = Pattern.compile("[A-Z]{3}[0-9]^0{3}");
        Matcher charRight = rightChar.matcher(invoice);
        p.matcher(invoiceCode);
        if(m.matches()) {
             System.out.println(invoice);
        else {
                 System.out.println ("B");
        //Checks for error C
        //Where the last three digits are not all zeros
        Pattern notZero = Pattern.compile("*{3}^0{3}");
        Matcher ZeroNot = notZero.matcher(invoice);
        p.matcher(invoiceCode);
        if(m.matches()) {
             System.out.println(invoice); 
             else {
                 System.out.println ("C");
     //name = checkFullName(name);
     //Error D = Name field has fewer than two words
     //Error E = Name field has more than four words
     //Error F = Name field has no comma
     //Error G = Name field has a bad title 
     //Error H = Name field has a bad initial 
    /*Have a lot more to do...
    * Still need to go through the same if statement or Try Block statements with this data:
    *      String fname = st.nextToken();
          String lname = st.nextToken();
          String price  = st.nextToken();
          String genre = st.nextToken();
          String orderDate = st.nextToken();
          String shipDate = st.nextToken();
    * But for now I would like to see an example of an if statement I could use
    * (if mine is even right) or catch statement- the rest of the project we look
    * for similar certia as defined in the reg exp for invoice
     /*Writes to Report in the Console
     * Prints data into two columns:
     * Invoice Code and Error Type
     //Prints both column Headings
     private void columnHeadings ()
     System.out.println (padL("",5) +
     padL("Invoice",20) +padL("",20)+
     padL("Error Code",40));
     //movie is the name of the text file
     private void printMovie(Movie aReport) {
     System.out.println(aReport.getInvoiceCode()+"\t"+
           aReport.getErrorType()+"\t");
  *This method pads the string start to the length newLength leaving the
  *string left justified and returning the result.
  private String padL (String start, int newLength)
     String result = new String (start);
     while (result.length() <= newLength) result += " ";
     return result;
  } // end padL
   * This method pads the string start to the length newLength leaving the
   * string right justified and returning the result.
  private String padR (String start, int newLength)
     String result = new String (start);
     while (result.length() <= newLength) result = " " + result;
     return result;
// end padRThanks a lot.

Similar Messages

  • Installer was unable to access a critical file/directory. Please try installing again. Error code 49.

    Installer was unable to access a critical file/directory. Please try installing again. Error code 49.  Tried multiple times. get the same error code, which gives no helpful info. "Support" just sends me in a circle, never getting to anything actually helpful.

    Launch Photoshop CC 2014 application from C: > Program Files > Adobe > Adobe Photoshop CC 2014.
    Once the Photoshop CC 2014 application is launched , click on Help menu.
    Select Updates option.
    Once the Updates are listed , close Photoshop cc 2014 and Creative Cloud application .
    Then click on Update button and try to update .

  • Im getting the following Installer was unable to access a critical file/directory. Please try installing again.(Error code: 43) Contact Customer Support

    I'M GETTING THE FOLLOWING ERROR
    Installer was unable to access a critical file/directory. Please try installing again.(Error code: 43) Contact Customer Support

    Error downloading Creative Cloud applications

  • Hi...  I just attempted to update CC.  Download itself appears to have happened, but when then I got this message...  Installer was unable to access a critical file/directory. Please try installing again.(Error code: 43) Contact Customer Support .... can

    Installer was unable to access a critical file/directory. Please try installing again.(Error code: 43) Contact Customer Support
    Any ideas?

    Hi  Serpent,
    Try the following Steps:
    open activity monitor and close all Adobe related applications
    navigate to: /Library/Application support/Adobe
    In that directory you will see a folder named OOBE - Rename that folder to OOBEold
    Navigate to: MAC HD /Application/Utilities directory
    In there you will see a folder called "Adobe Application Manager" - delete it
    Download the Adobe Cleaner Tool from here: http://helpx.adobe.com/creative-suite/kb/cs5-cleaner-tool-installation-problems/_jcr_conte nt/main-pars/accordion_container_1/accordion-par/accordion-item-1/accordion-item-par/proc e dure/proc_par/step_3/step_par/download/file.res/AdobeCreativeCloudCleanerTool.zip
    Open the Cleaner Tool and choose to clean "Creative Cloud" only.
    Download and install Creative Cloud again - https://ccmdls.adobe.com/AdobeProducts/KCCC/1/osx10/CreativeCloudInstaller.dmg
    Regards,
    Rave

  • Oracle Form 9i - How to catch for error code and error message?

    Hello:
    I'd like to catch for error code such as ORA-20001, ORA-28007 if the form is not success. I tried TOOL_ERR.CODE and TOOL_ERR.MESSAGE, but it returns 0 and no message.
    Thanks in advance,
    TD

    I got it.
    Thanks,
    TD

  • Upload a txt file,read that file,display po details using BAPI

    hi GURUS,
    CL_GUI_FRONTEND_SERVICES=>gui_upload to retrieve the file (upload the file).
    HOW TO USE THIS??? GV MORE DETAILS PLEASE...I WANT TO read TEST PO DATA.txt file Can you give me example how the test data( Header data and Item level data is used to fill the test PO data.txt file )
    Do i need to Use OPEN DATASET
    CLOSE dATASET command?
    how????
    points will be rewarded
    thanks

    Hi Avik,
    using  CL_GUI_FRONTEND_SERVICES=>gui_upload in a program.
    There are sample programs in the following link
    http://wiki.ittoolbox.com/index.php/Upload_and_download_SAP_transport_request
    Award points if useful
    Thanks,
    Ravee...

  • While local variable initialized inside try block compiler throws error???

    Check out this code where two local variables(one String and the other int type) is declared at the beginning of the method and initialized inside try block. now when i compile this app, it gives an error sayin' that Variables not been initialized. Can anyone tell me why compiler is throwin' an error message?
    Many thanks.
    import java.io.*;
    public class Test{
    public static void main(String[] args){
    String aa;
    int c;
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("EnterAnything:");
    try{
    aa = in.readLine();
    c = 1;
    catch(IOException e){
    System.out.println(e.getMessage());
    System.out.println(aa);
    System.out.println(c);
    }

    jfbriere,
    Thanks to u all.
    that every reference to the variable is necessarily preceded
    by execution of an assignment
    to the variable.But I've initialized the variable c and aa inside try block before referencing it as a parameter of println()?
    Can u clarify this?
    --DM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Text/File Reader that will resize/reformat Text for easy reading.

    I've used a couple of Text/File reader Apps; but with all of them,
    you have the choice of zooming out to see enough of a page to
    see an entire line of text, which is way too tiny to read, or zooming
    in so that it's easy to read, but then needing to scroll back and forth
    to read each line.
    Is there a reader that will display text large enough to read, and
    reflow/reformat the text so that it's all on the screen?
    Thanks, Jim.

    I found that Stanza does a great job reformatting most file types for reading on the iPodT. You do need the Mac OSX software for Stanza to transfer files to the iPodT so that you can read them with Stanza.
    I'm happy; but I wish the answer had been easier to find!
    Jim.

  • I got this error message today from Creative Cloud: "Installer was unable to access a critical file/directory. Please try installing again. Error Code: 49"

    It was working great up until just last week, now it's not working. What did Adobe change to cause this problem and prevent any further updates after that last update?
    When will Adobe fix it, without any action on my part. The whole idea of the Cloud was that this was supposed to take care of itself.

    Launch Photoshop CC 2014 application from C: > Program Files > Adobe > Adobe Photoshop CC 2014.
    Once the Photoshop CC 2014 application is launched , click on Help menu.
    Select Updates option.
    Once the Updates are listed , close Photoshop cc 2014 and Creative Cloud application .
    Then click on Update button and try to update .

  • Installer was unable to access a critical file/directory. Please try installing again.(Error code: 43) Contact Customer Support - iMac running 10.9.3

    So... whatz up with this?
    Thanks in advance for your help
    Cheers

    Toni_Toaster if you need to locate the compromised file permission location then you will want to review your installation log files.  You can find details on how to review your installation log files at Troubleshoot install issues with log files | CC - http://helpx.adobe.com/creative-cloud/kb/troubleshoot-install-logs-cc.html.
    In regards to the Exit Code 7 document - Error "Exit 6" or "Exit 7" | Install log | Read, write, system file errors | CS5, CS5.5 - http://helpx.adobe.com/creative-suite/kb/error-exit-6-exit-7.html.  The error is still possible with CC 2014 if the file permissions under the current User account have become compromised.  The steps to correct the file permissions is also still valid.

  • Installer was unable to access a critical file/directory. Please try installing again.(Error code: 43)

    Problems with installing the Creative cloud update - (Error code: 43). Anyone had this problem and found a fix for it?

    Creative Cloud chat support (all Creative Cloud customer service issues)
    http://helpx.adobe.com/x-productkb/global/service-ccm.html

  • [CS3 JS]  Reading TXT file content into String

    Hello,
    I'm currently wanting to display a dialog box that has a dropdown menu containing all countries of the world.
    I have an external txt file that contains a list of all countries.
    I thought I would simply read-in the contents of the 'txt' file into a string and use it for displaying the list.
    For example
    i Instead of the usual:
    > var myLandMenu = dropdowns.add({stringList:["A", "B"...], selectedIndex:0});
    i I thought of doing something like:
    > var myLandList = ....? HELP ?....
    > var myLandMenu = dropdowns.add({stringList:myLandList, selectedIndex:0});
    Is this the way to do it?
    What would be the way to read in the text file content as a string?
    Thanks in advance,
    Lee

    > var myLandList = ....? HELP ?....
    > var myLandMenu = dropdowns.add({stringList:myLandList, selectedIndex:0});
    It's hard to tell from context, but myLandList needs to be an array of strings.
    If the file has one element per line, this would be one way of handling the
    conversion:
    var file = File("~/countries.txt");
    file.open("r");
    var str = file.read();
    file.close();
    var myLandList = str.split(/[\r\n]+/);
    And assuming that this is ScriptUI and not the older ID UI, the menu creation
    would look more like:
    var myLandMenu = dropdowns.add(bounds, myLandList);
    myLandMenu.items[0].selected = true;
    -X
    for photoshop scripting solutions of all sorts
    contact: [email protected]

  • Continiously read a txt file

    Hello fellows,
    is there a way to read a *.txt file continiously without doing the simple while loop wich burns all the CPU ??
    This txt file is generated by another application that pick up messages from a pipe and register messages in the txt file.
    As a final goal the messages read in the txt file will control other executions in the vi.
    Attached files: vi in LabVIEW 8.0 and the txt file.
    Attachments:
    Zip.zip ‏6 KB

    Thanks for your interest ! !
    The process will be as follows:
    1-an application reads text in a serveur pipe and write it into the txt file.
    2-The LabVIEW vi reads in loop the txt file and sort out the txt value each time that's updated by the application running in parralel.
    The goal is to synchronize the labview execution with the new messages arriving in the txt file.
    Thanks for your suggestions on how can I continiously read the txt file and take an action in the vi each time the txt file is updated with new text.
    See you...

  • Please help with file reading component

    i am currently writing a program in which i need to have a JTable
    which displays data from a text file which can be selected from an
    option via a JList. I can get the info from the file into the JTable
    but for some reason which i can't figure out! the file reading method
    which i have written to read the data in the text file keeps reading the text file twice so i am getting duplicate data in the JTable. it may
    be easier to understand with the code i have supplied for the ListListener and the file reading method. the text file which is to be read contains data in the form - aName%anAddress%aBirthdate%aGender
    here is the code:-
    //class listening for JList selection
    class ListListener implements ListSelectionListener{
              public void valueChanged(ListSelectionEvent e){
    try{
    //send the selected index to file reading method
                   readFile(fileList.getSelectedIndex());
                   catch(IOException exception){
                   JOptionPane.showMessageDialog(
                                  PeopleJTable3.this,
                                  "File not found", "Error",
                                  JOptionPane.ERROR_MESSAGE);
              }//end of valueChanged
    //method to read a file given a specific index
    public void readFile(int fileNumber)throws IOException{
              BufferedReader keyboard = new
                   BufferedReader(new InputStreamReader(System.in));
    PrintWriter screen = new PrintWriter(System.out, true);
    //declare variables to enable separating the data in the file
    String fileName, name, address, birthdate, gender, line;
    int i=0;
    int lineLength,firstPercent,secondPercent, thirdPercent;
    PersonRecord[] group = new PersonRecord[20];
    final char PERCENT = '%';
    if(fileNumber == 0){
    fileName = new String("datafile.txt");
    //create filereader to read a byte stream from a file
    //oparameter has name of file;
    FileReader fr = new FileReader("datafile.txt");
    //create buffered reader object takes stream of characters
    //from filereader
    BufferedReader in = new BufferedReader(fr);
    line = in.readLine();
    // while (line != null){
    while( !line.equals("0")){
              //find second percentage
              firstPercent = line.indexOf(PERCENT);
              int a = firstPercent + 1;
              while(line.charAt(a) != '%'){
                   a++;
    //find third percentage
              secondPercent = a;
              int b = secondPercent + 1;
              while(line.charAt(b) != '%'){
                   b++;
              thirdPercent = b;
              //extract the name
              name = line.substring(0,firstPercent);
              //extract the address
              address = line.substring(firstPercent + 1, secondPercent);
              //extract the D.O.B.
              birthdate = line.substring(secondPercent + 1, thirdPercent);
    //extract overdraft amount;
    gender = line.substring(thirdPercent + 1, line.length());
    String[] tabEntry = {name,address,birthdate,gender};
    //add this row to JTable
    people.addRow(tabEntry);
    line = in.readLine();
    screen.println(i);//this was used to check that the
    //file was actually being read twice
    //from this method
    i++;
         }//end while loop
    in.close();
    }//end readFile
    if you can tell me why this read the file twice that would be fantastic!
    Cheers
    iain

    oh, that is right... the valueChanged() method will get called twice when you use a mouseclick, but if selecting from the keyboard it will only be called once. I'm not sure why it does that either, but what camickr suggested will fix it.
    Here is my substitution using the StringTokenizer..
    // you will need to import the class
    import java.util.StringTokenizer;
    // this will actually read the entire file until EOF
    while( (line = in.readLine()) != null )
         StringTokenizer st = new StringTokenizer( line, "%", false );
         // make sure there are at least 4 tokens in this line to read
         while( st.countTokens() == 4 )
              name = st.nextToken();
              address = st.nextToken();
              birthdate = st.nextToken();
              gender = st.nextToken();
         String[] tabEntry = {name,address,birthdate,gender};
         //add this row to JTable
         people.addRow(tabEntry);
    } //end while loopHere's the link to the StringTokenizer's API http://java.sun.com/j2se/1.3/docs/api/java/util/StringTokenizer.html
    good luck,
    .kim

  • Try/Return/Catch question

    The tutorial says no code is allowed between try and catch blocks, but one of the examples given has a return statement between try and catch blocks.
    Why is this ( [one of the answers from the tutorial|http://java.sun.com/docs/books/tutorial/essential/exceptions/QandE/answers.html] ) OK?
    public static void cat(File file) {
    RandomAccessFile input = null;
    String line = null;
    try {
    input = new RandomAccessFile(file, "r");
    while ((line = input.readLine()) != null) {
    System.out.println(line);
    return; //<--- Why is this code legal?
    } catch(FileNotFoundException fnf) {
    System.err.format("File: %s not found%n", file);
    } catch(IOException e) {
    System.err.println(e.toString());
    } finally {
    if (input != null) {
    try {
    input.close();
    } catch(IOException io) {
    Just want to understand the unstated exception to these cases.
    Thanks,
    David Yorke
    FNG

    You're reading it wrong.
    try {
      input = new RandomAccessFile(file, "r");
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      } // end of while loop
      return; //<--- Why is this code legal?
      // legal because it's still inside the try block
    }  // end of try block
    catch(FileNotFoundException fnf) {
      System.err.format("File: %s not found%n", file);
    catch(IOException e) {
      System.err.println(e.toString());
    finally {
      if (input != null) {
        try {
          input.close();
        catch(IOException io) {
    }

Maybe you are looking for

  • Can I set up MF4770n with BOTH usb cable AND network cable to router?

    My MF4770n is connected to desktop pc with usb cable. Can I also add the network cable to router capability so that my laptops can access the printer through my home network? Or, do I need to uninstall the printer and run setup all over? I know that

  • Can't print from Windows 8 through Airport

    Recently added a Windows 8 pc to my Airport network. After loading Bonjour to the PC, it finds the printer. However, it does not print a test page properly, just a single line about HP-PCL XL;3;0, etc, then blank sheets. Ideas?

  • Costing sheet in productin order

    Hi, When we are creting production order system is not taking the costing sheet automatically. But we confiugured all the things properly. We configured order type, cost component structure, costing variant, valuation variant everything. Please guide

  • SAP ECC 6 Upgrade to 2008 R2 and Virtualization success/failure stories

    Hi Sap community, I'm planning the following upgrade on my SAP Ecc 6.0 : Source CI : physical server on windows 2003 x64 SP2, Target CI : virtual server under vsphere 5.0 Windows 2008 x64 R2, Source DB : physical server on windows 2003 x64 SP2, SQL 2

  • Is there a script that will reset preferences in Illustrator?

    I'm using Illustrator CS6 and Illustrator CC on both Mac and PC. Holding down Ctrl-Alt-Shift or Command-Option-Shift while launching Illustrator does not work to reset the preferences. Does anyone know an easy way to reset preferences?