简体   繁体   中英

How can we find out the number of times the while loop lasted

while((MAP = inputFile.readLine()) != null) {
    System.out.println(MAP);
}

How can we find out the number of iterations performed by the while loop? In this textfile, they can be sometimes 5 lines of data, or 100 lines of data..If they are 5 lines, the while loop probably performed 6 loops. I want that number.

Any suggestions?

int count = 0; 
while((MAP = inputFile.readLine()) != null) { 
    System.out.println(MAP); 
    count++;
} 
System.out.println(count);

将while循环外部的变量设置为计数器,然后在while循环中递增计数器。


int iterations = 0;
while((MAP = inputFile.readLine()) != null) {
    System.out.println(MAP);
    iterations++;
}
int i = 0;
while((MAP = inputFile.readLine()) != null) {
    i++;
    System.out.println(MAP);
    // Some other stuff
}
System.out.println(i);

Set a variable to 0 before the while loop and increment the variable inside the while loop. Output the variable after the while loop.

如果可以使用java.io.LineNumberReader.getLineNumber()为什么还要自己做呢?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM