Does anyone know why this happens? I am doing a while loop to count records from an input stream. The program sees the input; there are three records in the text file that is set up. I just want to get a record count, so I have an incrementer inside of the loop that goes until a String variable (initialized as "") is != null. I have output statements set up to help me debug the issues, and the last record in the console is displayed as null, and it counts it as another record. I checked my file; I don't have any extra spaces or carriage returns or anything, so I'm OK on that end. Why does the while loop process a null record at the end? Shouldn't the loop be performed until it ISN'T null, then stop when it sees that it is?
Here is an example of the code:
As mentioned, everything is coming in and reading OK, but the loop is not stopping BEFORE the null value. How do I prevent this? Is there a way to get around it? I tried an if statement inside of the loop (if in != null then increment numRec), but it didn't work.
Sorry; the first line in the loop should be: in = input.readLine();
Joined: Sep 28, 2004
Also the code doesnt have the cuyly braces in the while loop.
Joined: Jan 29, 2005
Sorry; I was going off of memory and I just got done working 13 hours so my mind is a little whacked. The curly braces are in the code that I have (I actually opened it now). But, I tried your suggestion and it worked! Thanks! But why wouldn't the other way work - why would it loop through the last time being null? Pretend all of the correct syntactical things were present. I don't get that.
I tried this code, and it worked fine. (Note the if check). I'm not sure why when you used the if check it didn't work, but try it again.
And, for the record, I prefer this format to the while ( (in=input.readLine()) != null ) format; I find this much more readable.
Try the following as well; it's a little more readable; the logic is a little bit more straightforward (no need for the extra if):
[ April 01, 2005: Message edited by: Joel McNary ]
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Joined: Jan 29, 2005
Thanks Joel! This is great! I use eclipse and don't have the software right in front of me right now, but I am going to try this as soon as I get home.
As far as the if check, that is exactly what I did. I'll try it again though to see what happens. I personally am more comfortable doing it this way instead of the readLine() in the while condition because then the while condition is just doing one thing and not two, so I'm going to try this one.
Marilyn, I think the part I don't understand is that it says to perform the steps inside of the loop UNTIL it is equal to null. So if it checks it at the end AFTER it has performed everything, isn't that a hosed way of doing it? I know it's not you, but I am just trying to understand better.