java 我们如何找出while循环持续的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4610659/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 07:12:52  来源:igfitidea点击:

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

javawhile-loop

提问by razshan

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.

我们如何找出while循环执行的迭代次数?在这个文本文件中,它们有时可以是 5 行数据,或 100 行数据。如果它们是 5 行,那么 while 循环可能执行了 6 次循环。我要那个号码

Any suggestions?

有什么建议?

采纳答案by Phoenix

Set a variable external to the while loop to be a counter, and then increment the counter in the while loop.

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

回答by Falmarri

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

回答by Hans Hermans


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

回答by Dave McClelland

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

回答by mhaller

Why do it yourself if you can use java.io.LineNumberReader.getLineNumber()?

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

回答by Dallas Clark

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

在 while 循环之前将变量设置为 0,并在 while 循环内递增该变量。在 while 循环后输出变量。