java - Reading from STDIN via BufferedReader in while loop - Array only correct if System.out.println() is called within the loo

admin2025-04-21  4

I have this basic mechanism for loading STDIN into an array via BufferedReader and a while loop:

BufferedReader r = new BufferedReader(new InputStreamReader(System.in));        
int lineCount = 0;
String[] titles = new String[50000];    //File never has more than 50000 lines
while(r.ready()) {
    
    // Reading data using readLine and store in titles array
    String s = r.readLine();
    titles[lineCount++] = s;
}

When accessing the finished 'titles' array outside the while loop after this, it appears about half of the indexes are null. However, if I include a System.out.println() call within the loop, the finished array is fully populated as expected.

BufferedReader r = new BufferedReader(new InputStreamReader(System.in));        
int lineCount = 0;
String[] titles = new String[50000];    //File never has more than 50000 lines
while(r.ready()) {
    
    // Reading data using readLine and store in titles array
    String s = r.readLine();
    System.out.println(titles[lineCount-1] + " " + (lineCount - 1));
    titles[lineCount++] = s;
    
}

I gotta be missing something easy here, right? There's no threading involved. I've tried calling System.out.flush() instead of println, but that doesn't do the trick. Why is println seemingly required to get all lines correctly assigned to the array? (Again, only some and not all array indexes are null without the println statement within the loop.)

转载请注明原文地址:http://www.anycun.com/QandA/1745223775a90432.html