This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The basic job of the code is to read in a text report file downloaded from a mainframe and split it into a separate file for each site, with a file name based on the site number.
Programatically, the logic isn't too hard, but what is tripping me up is the scope of the if blocks. I am setting up the file name on the first record, and every time the site changes I close that file and open a new one. In my old mainfrme world, this would work, but I am unsure how to code it in java. (The compiler doesn't like my references to writer in both lines where I close it, and the write statement, because I created the variable inside the if statements.) Do I need to place the code inside the if block in a called method, and pass the BufferedWriter object in, and return a BufferedWriter object back, with an instance variable that I would then point at that object? My code follows:
Even worse, getting to the end of the while() black and starting over at the top makes all the variables declared in the while() go out of scope. This means that you'll have to declare the BufferedWrite outside of the while() as well.
I don't know how smart the compiler in figuring out whether the "if(first)" condition is true the first time through the while loop, so it might complain that writer "might not be initialized" when it's used in the "if(siteNo!=holdSite)" block. So you even have to set writer to some value, such as null, before the while loop.
AND THEN... you can use a null value for writer as the condition to identify the first time through the loop instead of using the separate "first" boolean.
AND... you've already calculated siteNo at the start of the while loop, so there's no need to recalculate it in the "if (siteNo!=holdSite)" block.
But wait... If I understand your intended logic correctly, you want to assign siteNo to holdSite inside the second if(). Otherwise, you'll close and reopen witer over and over.
This makes the innards of the if()s almost the same, with the writer.close() call being the only difference. You might as well collapse them together with the close() inside an if().
Some may argue that the last "optimization" comes only at the expense of understandability/maintainability. It's up to you.
Ryan [ May 11, 2005: Message edited by: Ryan McGuire ]