Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Unsure of this loop.

Status
Not open for further replies.

Dilenger4

Programmer
Nov 28, 2001
13
0
0
US
I was looking over an old program that somone had coded and im not sure of this loop. I would ask the person who coded this but i havent seen him in a while. I understand the logic but im not sure of the use of the loop.

If an array is constructed with 10 elements ie... int[9] then on the first iteration 11 bytes will be read since the offset is 0 and data length is 10. So an ArrayOutOfBounds Exception should be thrown. Right? I see that on the next line offset will be greater than data.length because 11 bytes have been read.


Also the condition is being tested before bytesRead is stored in offset. So the first time around offset will still have the value 0. Shouldn't offset += bytesread; come first?
code:--------------------------------------------------------------------------------
int[] data = new int[9]
int offset = 0;
int bytesRead = 0;

while(true){
bytesRead = in.read(data, offset, data.length-offset);
if(bytesRead == -1 || offset > data.length) break;
offset += bytesread;
}
Thanks for the help!
 
This is ridiculously inefficient. All that is needed is
bytesRead = in.read(data, offset, data.length);
with no loop. As long as there are 10 bytes available this
will fill the array.


read
public int read(byte[] b,
int off,
int len)
throws IOException
Reads up to len bytes of data from the input stream into an array of bytes.
 
Exactly. When i saw this done i was wondering what the use of the loop was. Thanks for your comment.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top