Home > Mobile >  Is there an advantage to using a for-loop over a while-loop in file reading?
Is there an advantage to using a for-loop over a while-loop in file reading?

Time:03-26

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.

CodePudding user response:

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.

CodePudding user response:

If you're going to use the for loop approach, at least put the "work" inside the loop body itself:

// 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.

  • Related