在文件读取中使用 for 循环比 while 循环有优势吗?
在做一些文件读取的练习题时,我遇到了一个问题。这个问题的性质要求我阅读该文件并可能中途停止。提出一个解决方案后,我想到了另一个解决方案,并想知道哪个会更有效 - (这里文件是 java.util.Scanner 类型) -
While-Loop
// create default values
byte loops = 0, sum= 0;
// loop while there is data and a non-negative sum
while(file.hasNextInt() && sum >= 0)
{
sum += file.nextInt();
loops++;
}
For-Loop强>
// create default values
byte loops = 0, sum = 0;
// loop while there is data and a non-negative sum
for(;file.hasNextInt() && sum >= 0;
sum += file.nextInt(), loops++);
#编辑深度# 目标:打印负和以及达到或声明其具有正和所需的循环次数。
While doing some practice problems with file reading, I came upon a question. The nature of this question required me to read the file and potentially stop partway through. After coming up with one solution, I thought of another and wondered which would be more efficient-(file is of type java.util.Scanner here)-
While-Loop
// create default values
byte loops = 0, sum= 0;
// loop while there is data and a non-negative sum
while(file.hasNextInt() && sum >= 0)
{
sum += file.nextInt();
loops++;
}
For-Loop
// create default values
byte loops = 0, sum = 0;
// loop while there is data and a non-negative sum
for(;file.hasNextInt() && sum >= 0;
sum += file.nextInt(), loops++);
#EDIT for depth#
Goal: print the negative sum and number of loops that it took to reach or state that it had a positive-sum.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这些实际上是相同的。你会发现很多事情可以用不同的方式来完成,有时甚至是截然不同的方式。在这种情况下,我倾向于倾向于对必须处理它的人(我和我的同事)来说更容易的代码。就我个人而言,我发现 while 循环更具可读性。使用 while 时,您不会遗漏结构的某些部分或以独特的方式使用它们,就像使用 for 循环一样。
我唯一担心的效率问题是您使用
byte
作为变量的类型。我对文件的大小或其中的数字一无所知,因此似乎很可能会溢出或下溢一个字节。特别是在 Java 中,字节是有符号的。These are virtually the same. You'll find a lot of things can be done in different ways, sometimes extremely different ways. When that's the case, I tend to lean towards the code that's easier for the humans who have to deal with it: me and my coworkers. Personally, I find the while loop is much more readable. With the while you're not leaving out parts of the structure or using them in a unique fashion like you are with the for loop.
My only efficiency concern is that you're using
byte
as the type for your variables. I know absolutely nothing about the size of the file or the numbers that are in it so it seems very possible that you could overflow or underflow a byte. Especially in Java where a byte is signed.如果您打算使用
for
循环方法,至少将“工作”放在循环体本身中:不过,就我个人而言,我会使用
while
方法因为您没有初始化任何变量并使用它们的状态来控制 for 循环,并且正在计算的值也在 for 循环之外使用。If you're going to use the
for
loop approach, at least put the "work" inside the loop body itself:Personally, though, I'd use
while
approach instead since you're not initializing any variables and using their state to control thefor
loop, and the values being computed are being used outside thefor
loop as well.