Your while loop condition is not correct it should be while(line != null), first of all line is initialized to empty string ("") so with current code the loop is never entered, secondary line = b.ReadLine(); should not be null until the file ends – from the StreamReader.ReadLine docs:
ReturnsString
The next line from the input stream, or null if the end of the input stream is reached.
Also this makes inner check if(line != null) obsolete.
...
string line = "";
// line is NOT null (it's empty) that's why
// while will not enter at all
while (line == null)
{
...
}
Let’s change while into for, let pesky line (which is declared out of loop, is check in while, in if etc.) be a loop variable:
// Wrap IDisposable into using; do not Close them expplicitly
using (StreamReader b = new StreamReader("students.txt"))
{
...
for (string line = b.ReadLine(); line != null; line = b.ReadLine())
{
if (line == "2") { num2++; }
...
}
...
}
3
Answers
line
is initialized to""
, so thewhile
loop is never entered. The condition should beline != null
, notline == null
like you currently have.Your
while
loop condition is not correct it should bewhile(line != null)
, first of allline
is initialized to empty string (""
) so with current code the loop is never entered, secondaryline = b.ReadLine();
should not benull
until the file ends – from theStreamReader.ReadLine
docs:Also this makes inner check
if(line != null)
obsolete.Your
while
is not correct; just have a look:Let’s change
while
intofor
, let peskyline
(which is declared out of loop, is check inwhile
, inif
etc.) be a loop variable: