Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Using bufferedReader to write contents of text file into an object array.

  1. #1
    Junior Member
    Join Date
    May 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Using bufferedReader to write contents of text file into an object array.

    I'm fairly new to JAVA and taking a class. One of the big parts of my assignment is to read from a text file and write those values to an array.

    For the most part, I got it to work where it will read in the values and my object array will populate.

    The text file is along these lines (item name and corresponding price...first line shows number of items):

    6
    item1 250
    item2 350
    item3 1050
    item4
    item5 1610
    item6 1505

    My problem comes about when it hits that "item4" line. I want it to not only add that item to my array, but to assign a value of "0" for that missing data. When I go into the text file and put in that zero, everything works beautifully. When I run it with that blank, it will skip the line entirely. I know that every time there is a "null" it throws me into NoSuchElementException, but I just don't know how to handle that blank the way I need it to.

    My code for this section is as follows:
        public void readArray (String fileName)
         {
     
           File inFile = new File(fileName);
           BufferedReader bufReader;
           FileReader fileReader;
           StringTokenizer tokenizer;
           String line, item;
           double price;
           int i =0;
     
           try 
           {
               fileReader = new FileReader(inFile);
               bufReader = new BufferedReader(fileReader);
     
     
     
               Scanner scan = new Scanner(inFile);
               n = scan.nextInt();
               stuff = new Inventory[n];
     
     
                   while((line = bufReader.readLine()) != null) 
                   {
                         tokenizer = new StringTokenizer(line); 
                         try
                         {
     
                               while(true)
                               {
                                    item = tokenizer.nextToken();
                                    price = Double.parseDouble(tokenizer.nextToken());
     
                                    stuff[i] = new Inventory(item,price);
     
                                    i++;
     
                               }
                         }
                         catch(NoSuchElementException exception)
                         {
                            //what do I even do here?
                         }
                }
     
            }
     
            catch(FileNotFoundException exception)
            {
                System.out.println("Unable to open file.  Check if the file exists or path is correct" +inFile.getAbsolutePath());
                System.exit(0);
            }
            catch(IOException exception)
            {
                System.out.println("Could not open input file" +exception.getMessage());
            }    
        }

    I even tried just doing
    stuff[i] = new Inventory(item,0);
    just to see if it would pick up that row, and it doesn't. It will assign a 0 to every item, but completely skip item4.


    Thanks guys!
    Last edited by aznenginerd; May 8th, 2012 at 02:05 PM.


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,751
    Thanks
    45
    Thanked 1,975 Times in 1,949 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    The StringTokenizer has a method you should call to test if there is a next token before calling the nextToken() method. If there is no token, use the default value for the missing token.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    May 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    I had tried to do it with "hasMoreTokens" but I couldn't get it to work correctly. It would still throw that "NoSuchElementException" and throw it out of the loop before it even writes to the array...how would I successfully implement something like that?

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,751
    Thanks
    45
    Thanked 1,975 Times in 1,949 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    You need to check for more tokens for EVERY time you call nextToken().
    if(has more) {
       OK to use nextToken()
    }
    if(has more) {
      Ok to use nextToken()
    }
    etc
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    May 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    I changed my loop to the following:

    while((line = bufReader.readLine()) != null) 
                   {
                         tokenizer = new StringTokenizer(line); 
                         more = tokenizer.hasMoreTokens();
     
                         try
                         {
     
     
                               while(true)
                               {
                                   item = tokenizer.nextToken(); 
     
                                   if (more = true)
                                   {
                                   price = Double.parseDouble(tokenizer.nextToken());
                                   stuff[i] = new Inventory(item,price); 
                                   }
     
                                   if (more = false)
                                   {
                                   stuff[i] = new Inventory(item);
                                   }
     
     
                                    i++;
     
                               }
                         }

    I still get the same problem, however, where it entirely skips that line that doesn't have the second element. Did I not implement that correctly?

  6. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,555
    Thanks
    24
    Thanked 304 Times in 286 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    You have to reevaluate tokenizer.hasMoreToken() each time you use the tokenizer.nextToken() method.

    Explain to me the reason you have the while loop (the one that says while(true)).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,751
    Thanks
    45
    Thanked 1,975 Times in 1,949 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    Did I not implement that correctly?
    Yes, you did not implement the logic correctly.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    May 2012
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    I had the while (true) loop to fill the array. I had tried to use a for loop, but every time it would hit that null at the end of the line, it would go to the noSuchElementException and initialize the i count back to zero...essentially my array kept overwriting itself. I would prefer the for loop to fill the array, but I saw an example somewhere where they use the while loop and it gave me less errors. What would be the best way to handle this using a for loop?

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    18,751
    Thanks
    45
    Thanked 1,975 Times in 1,949 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    if(has more) {
       OK to use nextToken()
    }
    if(has more) {
      Ok to use nextToken()
    }
    etc

    You need a way to exit the loop. Use a break statement when there are no more tokens.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,555
    Thanks
    24
    Thanked 304 Times in 286 Posts

    Default Re: Using bufferedReader to write contents of text file into an object array.

    Ok, tell me if I am wrong, but here's how I would expect your original code to run:
    ENTER WHILE (outer):
    line = "item1 250"
    tokenizer = new StringTokenizer(line);
    ENTER TRY:
    ENTER WHILE (inner):
    item = "item1"
    price = 250.0
    stuff[0] = new Inventory(item,price);
    CONTINUE WHILE (inner):
    item = tokenizer.nextToken() == NoSuchElementException
    ENTER CATCH:
    do nothing
    CONTINUE WHILE (outer):
    line = "item2 350"
    tokenizer = new StringTokenizer(line);
    ENTER TRY:
    ENTER WHILE (inner):
    item = "item2"
    price = 350.0
    stuff[1] = new Inventory(item,price);
    CONTINUE WHILE (inner):
    item = tokenizer.nextToken() == NoSuchElementException
    ENTER CATCH:
    do nothing
    CONTINUE WHILE (outer):
    line = "item3 1050"
    tokenizer = new StringTokenizer(line);
    ENTER TRY:
    ENTER WHILE (inner):
    item = "item3"
    price = 1050.0
    stuff[2] = new Inventory(item,price);
    CONTINUE WHILE (inner):
    item = tokenizer.nextToken() == NoSuchElementException
    ENTER CATCH:
    do nothing
    CONTINUE WHILE (outer):
    line = "item4"
    tokenizer = new StringTokenizer(line);
    ENTER TRY:
    ENTER WHILE (inner):
    item = "item4"
    price == NoSuchElementException
    ENTER CATCH:
    do nothing
    CONTINUE WHILE (outer):
    line = "item5 1610"
    tokenizer = new StringTokenizer(line);
    ENTER TRY:
    ENTER WHILE (inner):
    item = "item5"
    price = 1610.0
    stuff[3] = new Inventory(item,price);
    CONTINUE WHILE (inner):
    item = tokenizer.nextToken() == NoSuchElementException
    ENTER CATCH:
    do nothing
    CONTINUE WHILE (outer):
    line = "item6 1505"
    tokenizer = new StringTokenizer(line);
    ENTER TRY:
    ENTER WHILE (inner):
    item = "item6"
    price = 1505.0
    stuff[4] = new Inventory(item,price);
    CONTINUE WHILE (inner):
    item = tokenizer.nextToken() == NoSuchElementException
    ENTER CATCH:
    do nothing
    EXIT WHILE (outer)

    Now, with the while(true) loop, you would just be getting a ton of NoSuchElementExceptions since you would continue to try to tokenize past the end of the line. If I'm correctly, you probably wouldn't even notice, since you are catching those errors, but doing nothing when you do. What I mean by all of this is that the inner while loop (or any inner loop) is unnecessary in this situation (assuming you don't have more than one Inventory Item on each line).
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. Replies: 0
    Last Post: December 15th, 2011, 12:14 PM
  2. Replies: 8
    Last Post: March 25th, 2011, 02:34 PM
  3. Read a text file and parse the contents of file
    By HelloAll in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: March 3rd, 2011, 04:47 AM
  4. Reading in entire contents of text file to one string
    By fortune2k in forum File I/O & Other I/O Streams
    Replies: 9
    Last Post: December 12th, 2010, 06:03 PM
  5. write text to a file help
    By wolfgar in forum File I/O & Other I/O Streams
    Replies: 8
    Last Post: November 24th, 2009, 07:36 AM