[SOLVED] 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)-


// 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();


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


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.

Answered By – Corey Ogburn

Answer Checked By – Gilberto Lyons (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *