简体   繁体   English

在文件读取中使用 for 循环比 while 循环有优势吗?

[英]Is there an advantage to using a for-loop over a while-loop in file reading?

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)-在想出了一个解决方案之后,我想到了另一个,想知道哪个会更有效率-(文件类型为 java.util.Scanner here)-

While-Loop While 循环

// 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 For循环

// 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. #EDIT for depth# 目标:打印负和和达到它所花费的循环数或 state 它有一个正和。

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.就个人而言,我发现 while 循环更具可读性。 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.随着时间的推移,您不会遗漏部分结构或以独特的方式使用它们,就像您使用 for 循环一样。

My only efficiency concern is that you're using byte as the type for your variables.我唯一关心的效率问题是您使用byte作为变量的类型。 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.特别是在一个字节被签名的 Java 中。

If you're going to use the for loop approach, at least put the "work" inside the loop body itself:如果您打算使用for循环方法,至少将“工作”放在循环体内:

// create default values
byte loops = 0, sum = 0; 
// loop while there is data and a negative sum 
for(;file.hasNextInt() && sum >= 0; loops++) {
    sum += file.nextInt();
}

Personally, though, I'd use while approach instead since you're not initializing any variables and using their state to control the for loop, and the values being computed are being used outside the for loop as well.不过,就个人而言,我会改用while方法,因为您没有初始化任何变量并使用它们的 state 来控制for循环,并且正在计算的值也在for循环之外使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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